Generics — why a type parameter instead of any?
Answer out loud or in your head first, then compare.
Answer
Generics keep the relationship between types instead of throwing it away with any.
TypeScript
function first<T>(items: readonly T[]): T | undefined {
return items[0];
}
const name = first(['Anna', 'Ola']); // string | undefined
interface ApiResult<T> {
data: T;
requestId: string;
}To be precise: T is a type parameter; the compiler often infers it. For an operation that needs id, you can constrain T with extends { id: string }.
Pitfall: a fetchJson<T> function doesn't prove the network response has type T. Validating the data is still a separate step.
How did it go? Be honest — “Not yet” puts the question on your review list.
Related questions
- B-P13 · What is a generic type? — JavaScript, TypeScript and Node.js