Senior LevelJavaScript & TypeScript
How do TypeScript generics, conditional types, and mapped types work?
❓ Interview Prompt: Explain generic constraints, conditional types (extends/infer), and mapped types (keyof, Record, Partial, Pick).
Generics:
Type parameters that make functions, classes, and interfaces work with any type while maintaining type safety:
function identity<T>(value: T): T { return value; }
Generic Constraints:
Restrict generic types with extends: <T extends { id: number }>
Conditional Types:
T extends U ? X : Y — type-level if/else.
infer keyword extracts types: type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
Mapped Types:
Transform existing types:
•
Partial<T> — all properties optional.•
Required<T> — all properties required.•
Pick<T, K> — select specific properties.•
Omit<T, K> — exclude specific properties.Code Implementation Example
typescript
// Generic function with constraint
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { name: 'Alice', age: 28 };
getProperty(user, 'name'); // string
getProperty(user, 'age'); // number
// Conditional type with infer
type UnpackPromise<T> = T extends Promise<infer U> ? U : T;
type Resolved = UnpackPromise<Promise<string>>; // string💡Generic constraints, conditional types with infer, and custom mapped types.
🎯 Interview Key Takeaway
Use generics with keyof constraints for type-safe property access. Use conditional types with infer for type extraction.
#Generics#Conditional Types#Mapped Types#Senior
Back to all JavaScript & TypeScript Questions→