# [Advent of Typescript 2024] 6/25 (Generic Constraints) ###### tags `TypeScript` <div style="display: flex; justify-content: flex-end"> > created: 2025/01/23 </div> ## 題目 https://www.adventofts.com/events/2024/6 ## Generic Constraints 有時候使用泛型別時又希望可以規範一些型別,這個時候就可以用 `泛型別 + extends`: ```typescript // 這裡希望可以收一個泛型別,但是我又想要規範裡面有 length property function loggingIdentity<Type extends Indentity>(arg: Type): Type { console.log(arg.length); return arg; } // 所以就可以用 泛型別 + extends 去規範這個泛型別 type Indentity = { length: number } function loggingIdentity<Type extends Indentity>(arg: Type): Type { console.log(arg.length); return arg; } // 因為被規範成一定要有 { length: number } 了,所以就不能亂丟 loggingIdentity(12) loggingIdentity({ length: 1231 }) // 只要符合就行 loggingIdentity({ length: 1231, name: 'lun' }) ``` ## 參考資料 - [Generic Constraints](https://www.typescriptlang.org/docs/handbook/2/generics.html#generic-constraints)
×
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