Web Development
TypeScript
Subjective
Oct 04, 2025
Explain advanced generic constraints and conditional types.
Detailed Explanation
Advanced generics combine constraints, conditional types, and inference for powerful type transformations.
Generic Constraints:
interface Lengthwise {
length: number;
}
function loggingIdentity(arg: T): T {
console.log(arg.length);
return arg;
}
loggingIdentity('hello'); // Works
loggingIdentity([1, 2, 3]); // Works
loggingIdentity(3); // Error: number does not have length
Conditional Types:
type NonNullable = T extends null | undefined ? never : T;
type ApiResponse = T extends string ? { message: T } : { data: T };
// Usage
type StringResponse = ApiResponse; // { message: string }
type NumberResponse = ApiResponse; // { data: number }
Advanced Pattern with Infer:
type ReturnType = T extends (...args: any[]) => infer R ? R : never;
type Parameters = T extends (...args: infer P) => any ? P : never;
// Extract nested array type
type Flatten = T extends (infer U)[] ? U : T;
type StringArray = Flatten; // string
type NumberType = Flatten; // number
Benefits:
• Enable complex type transformations
• Create flexible, reusable type utilities
• Provide compile-time guarantees
• Support advanced API design patterns.
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts