Typescript Generic Constraints: Apply constraints to generics for more precise type definitions.
In TypeScript, generic constraints allow you to enforce certain rules on generic types, making your type definitions more precise and your code safer.
Constraints are specified using the extends
keyword, which restricts what types can be used as generic arguments.
Here are some examples of how to use generic constraints in TypeScript:
1. Basic Constraints with extends
You can constrain a generic type to extend a specific type, ensuring that only types compatible with that constraint are accepted.
In this example, T
is constrained to types that have a name
property of type string
.
2. Constraining to a Union of Types
You can restrict a generic to a specific set of types by using union types in the constraint.
Here, T
can only be a string
or an array (any[]
), both of which have a length
property.
3. Constraining to Class Instances
You can use classes as constraints to ensure the generic type is an instance of a particular class.
In this example, T
is constrained to be of type Animal
or any subclass of Animal
, so you can call sound()
on animal
.
4. Multiple Constraints with &
You can apply multiple constraints by combining them with &
. This requires the generic type to satisfy all specified constraints.
Here, T
is constrained to types that have both id
and name
properties.
5. Using keyof to Constrain to Keys of a Type
You can use keyof
to constrain a generic type to be one of the keys of another type.
Here, T
is constrained to be one of the keys of the Person
type (id
, name
, or age
), so you can't pass a key that doesn't exist on Person
.
6. Default Values with Constraints
You can set a default type with a constraint to avoid having to specify the type in every call.
In this example, if no type argument is provided, T
defaults to { id: number }
.