Generics
| Your first T | |
| Let TS infer T | |
| Explicit type args | |
| Generic array helpers |
Your first T
A type parameter is a placeholder that the caller fills in with a real type. The name T is tradition for a first placeholder. One generic function below replaces a whole family of single type copies.
function first<T>(items: T[]): T | undefined {
return items[0];
}
Let TS infer T
You rarely write the type argument because TypeScript reads it from the value you pass. Passing strings makes T string with no extra markup. Inference keeps generic calls as short as plain calls.
const n: number | undefined = first([1, 2, 3]);
const s: string | undefined = first(["a", "b"]);
Explicit type args
Sometimes inference picks a wider type than you want, or there is no argument to read from. Angle brackets after the name pin the type down by hand. Explicit arguments also document intent for the next reader.
const xs: number[] = [];
const f: number | undefined = first<number>(xs);
Generic array helpers
Library helpers like map and filter are generic functions built into every array. The callback return type becomes the new element type automatically. Chaining them transforms lists without a single loop in sight.
const nums: number[] = [1, 2, 3];
const doubled: number[] = nums.map((n) => n * 2);
Next: Constraints
Article author: Arthur Isaev