TypeScript Developer interview question · Most asked
What are generics and how do constraints work?
Summary
Generics are type parameters (<T>) that let functions, classes and types work over many types while preserving type relationships. Constraints (<T extends Something>) restrict what T can be so you can safely use its members.
Longer Answer
Example: function first<T>(arr: T[]): T | undefined returns the same element type it receives. keyof constraints relate parameters: function get<T, K extends keyof T>(obj: T, key: K): T[K]. Defaults (<T = string>) and inference from arguments make generic APIs ergonomic. Avoid unnecessary generics: if T is used only once, a plain type is clearer.
Code Example
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { id: 1, name: "Ana" };
const n = getProp(user, "name"); // string
// getProp(user, "age"); // Error: '"age"' not in keyof user
function longest<T extends { length: number }>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}
Key Points
- Type parameters preserve relationships
extendsconstraintsK extends keyof T→T[K]- Inference from arguments
- Don't over-genericize
More most-asked TypeScript Developer questions
- What is TypeScript and what problems does it solve?
- What are the differences between `interface` and `type` aliases?
- Explain `any`, `unknown` and `never`.
- What is type narrowing and what techniques does TypeScript support?
- What are discriminated unions and why are they powerful?
- Which built-in utility types do you use most, and what do they do?
- What is structural typing in TypeScript?
- What are mapped types? Show how `Partial` or `Readonly` could be implemented.