TS 高階技巧
假期在家中無意間刷到了一篇 TS 技巧的文章,自己嘗試了一下,覺得確實挺不錯的,因此這裡做一些記錄。
活用提示
在使用 ts 的 interface
做定義宣告時,一般寫註釋時都習慣性的使用單行註釋 // ...
,雖然在看對應的 interface
時我們能知道是什麼內容,但是在使用時往往只有個光禿禿的宣告,後期維護時會感覺特別雞肋:
但是如果這樣寫註釋的話,在註釋的呈現上會更利於閱讀:
對返回引數、元件傳參宣告 等會經常去查閱的 ts 宣告部分,可使用多行註釋的寫法,讓使用體驗更友好。
interface & type
TypeScript 中有兩種定義介面型別的方法,分別是: interface(介面)
、 type alias(類型別名)
,它們之間是能夠自身繼承、相互繼承的:
// interface 繼承 interface interface Item { name: string } interface SubItem extends Item { age: number } // type alias 繼承 type alias type Shape = { name: string } type SubShape = Shape & { age: number } // interface 繼承 type alias type Data = { name: string } interface SubData extends Data { trueage: number } // type alias 繼承 interface interface List { name: string } type SubList = List & { age: number }
這兩者使用上特別相似,但也稍微有些不一樣的地方
1. 寫法不同
// interface(偏向於:類、例項) interface IProps { name: string funcA: (param1: number) => void } // type alias(偏向於:字面量形式的值/物件、函式) type data = { name: string } type funcA = (param1: number) => void // 函式的 ts 宣告的三種寫法 const func1: funcA = (p) => {} // type 宣告 const func2: IProps['funcA'] = (p) => {} // interface 宣告 const func3 = (p: number): void => {} // 內聯式宣告
目前專案中使用面向物件的寫法會多一些,因此 類、例項 的出現比例會打一些,對於單獨 .ts 檔案內宣告的函式可用 type 做宣告會更方便一些
2. 其它不同
其它部分就直接貼上看到的文章了,就不贅述了
typeof
這一點先前確實沒關注過,不過對於有預設值的型別,確實會節省不少時間:
const defaultProps = { /** 這裡寫屬性的提示:姓名 */ name: '' } /** 這裡寫整體的提示 */ type IProps = typeof defaultProps; // 這裡 hover 上時會有提示 const myData: IProps = defaultProps
keyof
這個單獨來看用途可能不是很大,但是封裝通用函式時,沒有這個可能問題很大:
按照以前的寫法,所獲得的值會丟失型別,這 ts 就有些尷尬:
使用 keyof 方法改寫後,我們來看看效果:
這樣我們便能夠從方法中推斷出對應物件的型別了,確實方便了很多。
參考文章
- TypeScript: Interfaces vs Types
- [TypeScript 中提升幸福感的 10 個高階技巧](
「其他文章」