Generics in TypeScript
Functions and types that work over any type.
function first<T>(items: T[]): T | undefined {
return items[0];
}
function pluck<T, K extends keyof T>(items: T[], key: K): T[K][] {
return items.map((item) => item[key]);
}
interface Box<T> {
value: T;
map<U>(fn: (value: T) => U): Box<U>;
}
const names = pluck([{ id: 1, name: "ada" }], "name");
How it works
<T>makes the input and output types related.K extends keyof Tconstrains a key parameter.T[K]indexes the type to get the value type.
Keywords and builtins used here
KTconstextendsfunctioninterfacereturn
The run, in numbers
- Lines
- 14
- Characters to type
- 299
- Tokens
- 121
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 73 seconds.
Step 1 of 4 in Type parameters, step 1 of 20 in Generics.