[Typescript] Generics constraint
typescript constraint generics
2023-09-14 09:00:45 时间
Assume we have the following code:
interface HasId {
id: string
}
interface Dict<T> {
[k: string]: T
}
function listToDict<T>(list: T[]): Dict<T> {
const dict: Dict<T> = {}
list.forEach((item) => {
// Property 'id' does not exist on type 'T'.
dict[item.id] = item
})
return dict
}
We want to have restraint that, each T should contians `id`:
interface HasId {
id: string
}
interface Dict<T> {
[k: string]: T
}
// T extends HasId
function listToDict<T extends HasId>(list: T[]): Dict<T> {
const dict: Dict<T> = {}
list.forEach((item) => {
dict[item.id] = item
})
return dict
}
相关文章
- [Typescript] Wrap an function with Identity function to provide clean Type API
- [Typescript] Creating a Dynamic Function with Variable Arguments
- [Typescript] 109. Hard - Length of String 2
- [Typescript] 65. Medium - Zip
- [Typescript] Typescript Enums vs Booleans when Handling State
- [Typescript] Get full type safe for discriminatedUnion type with 'type' & 'subtype' (2 levels)
- [Typescript] 24. Medium - Type Lookup
- TypeScript 的 generic 函数
- TypeScript里的工具类型Partial的用法
- TypeScript里的混合类型