function first<T>(arr: T[]): T | undefined {
return arr[0];
}
const n = first([1, 2, 3]); // number | undefined
const s = first(["a", "b"]); // string | undefined
Generics are type parameters. They let a function, type or class work with many types while keeping the link between the input type and the output type. Use them instead of any because any throws that link away.
In first<T>, whatever element type goes in comes back out. Pass numbers, get a number. Pass strings, get a string. TypeScript usually infers T from the arguments, so you rarely write it yourself.
With any, the function would accept anything but also return any. The caller then loses all type information and autocompletion. Mistakes are not caught.
Generics can be limited with extends to require a certain shape. They can also have default types.
Typical uses:
- collection helpers, like
firstorgroupBy - API response wrappers, like
ApiResponse<T> - hooks, such as
useState<T> - reusable components
- Type parameters keep the link between the input type and the output type.
- TypeScript usually infers the type parameter from the arguments.
anythrows away type information, while generics keep it.- You can limit a generic with
extendsand give it a default type.
Read more
- Generics (https://www.typescriptlang.org/docs/handbook/2/generics.html)typescriptlang.org