Try   HackMD

TypeScript 常用取法

取得型別

取得陣列中項目的型別

const list = [666, 'bruh', true] as const type Item = typeof list[number] // true | "bruh" | 666 // 💡 拆解步驟: type List = typeof list type ItemOfList = List[number]

🎡 TS Playground

取得物件裡的值的型別

const myObject = { small: 16, medium: 20, large: 24, } as const type Value = typeof myObject[keyof typeof myObject] // 16 | 20 | 24 // 💡 拆解步驟: type MyObject = typeof myObject type KeyOfMyObject = keyof MyObject type ValueOfMyObject = MyObject[KeyOfMyObject]

🎡 TS Playground