[Typescript] Generics constraint
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
}