Generics | Typescript
Hello World of Generics#
We can call it in one of two ways.
Working with Generic Type Variables#
Generic Types#
We could also have used a different name for the generic type parameter in the type
We can also write the generic type as a call signature of an object literal type:
Generic interface
In a similar example, we may want to move the generic parameter to be a parameter of the whole interface.
Generic Classes#
A generic class has a similar shape to a generic interface.
As we covered in our section on classes, a class has two sides to its type: the static side and the instance side. Generic classes are only generic over their instance side rather than their static side, so when working with classes, static members can not use the class's type parameter.
Generic Constraints#
To fix that, we'll create an interface that describes our constraint.
Because the generic function is now constrained, it will no longer work over any and all types:
Instead, we need to pass in values whose type has all the required properties:
Using Type Parameters in Generic Constraints#
You can declare a type parameter that is constrained by another type parameter.
For example, here we'd like to get a property from an object given its name.
We'd like to ensure that we're not accidentally grabbing a property that does not exist on the obj, so we'll place a constraint between the two types:
Using Class Types in Generics#
When creating factories in TypeScript using generics, it is necessary to refer to class types by their constructor functions. For example,
A more advanced example uses the prototype property to infer and constrain relationships between the constructor function and the instance side of class types.