How do generics work? Show a generic function, a constraint and a generic React component.
Generics let a function, type or component work with many types while keeping the relationship between input and output types. They are type parameters, written <T>.
Key ideas
- Inference: usually you do not write
<T>at the call site; TypeScript infers it from the arguments. - Constraints:
<T extends { id: string }>requiresTto have at least anid. - keyof with generics:
<T, K extends keyof T>ties a key to the object it belongs to, sogetProp(user, 'nmae')is an error. - Defaults:
<T = string>.
Example
ts
function first<T>(items: readonly T[]): T | undefined {
return items[0];
}
const n = first([1, 2, 3]); // number | undefined
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { id: 'u1', age: 30 };
const age = getProp(user, 'age'); // number
// getProp(user, 'nmae'); // error
function byId<T extends { id: string }>(items: T[]): Record<string, T> {
return Object.fromEntries(items.map(i => [i.id, i]));
}tsx
type ListProps<T> = {
items: T[];
renderItem: (item: T) => React.ReactNode;
getKey: (item: T) => string;
};
function List<T>({ items, renderItem, getKey }: ListProps<T>) {
return <ul>{items.map(i => <li key={getKey(i)}>{renderItem(i)}</li>)}</ul>;
}
// T is inferred as { id: string; name: string }
<List items={users} getKey={u => u.id} renderItem={u => u.name} />;Follow-up questions interviewers ask
Try answering each one before you open it.
How do you write a generic arrow function in a .tsx file?
const id = <T,>(x: T) => x; The trailing comma (or <T extends unknown>) stops the parser from reading <T> as a JSX tag.