[TS] Type Guard and Narrowing
此篇為各筆記之整理,非原創內容,資料來源可見下方連結與文後參考資料。
- Narrowing @ TypeScript Handbook
- Type guards and assertion functions @ Tackling TypeScript
Narrowing
Narrowing 指的是將某一個可能為多種型別的變數,縮限成某單一種型別。
透過 Type Guards 可以讓 TypeScript 在 compile 階段,避免開發者使用到不屬於該型別的方法,並且可以作為「當型別為 ... 才 ... 的操作」。