--- tags: blog --- # TypeScript 常用取法 從**值**取得**型別**。 ## 取得陣列中項目的型別 ```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](https://www.typescriptlang.org/play?#code/MYewdgzgLgBANgS2jAvDA2gNmwGhgcgCMAnAVwAt88oyBTAXRgEMIZRIoAoTqATwAdaMAJJRaAW1Qw+gkADN4SKOjClxhWsUYB6bTGl0YAHxgAiEhVPGY2TN10xAvBuBCnZiAxo0DHkYFNrQPpZgLH+eASEAGSUpGVp5RWhAwRExcQB5OVDkNFTlVXVNeiA) ## 取得物件裡的值的型別 ```typescript= 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](https://www.typescriptlang.org/play?#code/MYewdgzgLgBAtgTwPICMBWBTYsC8MDeAUDDBHAIYA2lAXDAIwBsANMfBgCYCWArnHQCYADKxKVyAJwDmGQQBZWAXxjkIMUJCiFCUBAAcMMAGpUehvLoMgAZvGTosUANoBrDAhsxLGT4lSZsAF0YAHoQhkYYAB8YYWjYuW0wmEBeDcBCnZhAMaNAY8jAU2tAfSzALH+dfUMAWXsA3C9S30rHEoMYAGl3JGsK-0cYPDcPW06HbEbDE0ozdsGqnpgpxydW5A76oKA)
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up