1/2/2024[edited at: 1/11/2024]
Expressing Constraints with Generics in TypeScript
Tags: typescript
In the block of code above, if we only use T
as the type of list
, TypeScript will complain that T
does not have a property called id
. On the other hand, if we only use HasId, we only get the property id
on IDE's suggestion when typing dict.
. TypeScript doesn't know the type of the value of dict
is T
. We need to use T extends HasId
to express the constraint that T
must have a property called id
and it has some other properties.