Advanced Generics in TypeScript
Advanced Generics in TypeScript
Section titled “Advanced Generics in TypeScript”Generic Constraints with keyof
Section titled “Generic Constraints with keyof”function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] { return obj[key];}
const user = { name: "Alice", age: 30, email: "alice@test.com" };const name = getProperty(user, "name"); // type: stringconst age = getProperty(user, "age"); // type: numberConditional Generic Return Types
Section titled “Conditional Generic Return Types”type IsString<T> = T extends string ? "yes" : "no";type A = IsString<string>; // "yes"type B = IsString<number>; // "no"The infer Keyword
Section titled “The infer Keyword”type Unpack<T> = T extends Array<infer U> ? U : T;
type StringArr = string[];type ElementType = Unpack<StringArr>; // stringReal Project Example
Section titled “Real Project Example”// Type-safe event emittertype EventMap = { userCreated: { id: string; name: string }; userDeleted: { id: string }; error: { message: string; code: number };};
class TypedEventEmitter<T extends Record<string, unknown>> { emit<K extends keyof T>(event: K, data: T[K]): void { console.log(`Event: ${String(event)}`, data); }
on<K extends keyof T>(event: K, handler: (data: T[K]) => void): void { // Register handler }}
const emitter = new TypedEventEmitter<EventMap>();emitter.emit("userCreated", { id: "1", name: "Alice" });Interview Questions
Section titled “Interview Questions”Easy: What is keyof used for with generics?
Medium: How does the infer keyword work?
Hard: Design a type-safe event emitter using generics.