Practice & Assessment
Test your understanding of Generics
Multiple Choice Questions
5What does T extends { name: string } mean in a generic function?
What does Omit<User, 'password'> produce?
What does ReturnType<typeof fn> give you?
When TypeScript infers T in identity<T>(value: T): T, what happens?
What does Partial<User> do to User's required properties?
Coding Challenges
1Build a generic cache with TTL
Implement a generic Cache<T> class with a set(key: string, value: T, ttlMs: number) method that stores a value with an expiry timestamp, a get(key: string): T | null method that returns the value if not expired and null otherwise, and a delete(key: string): void method. The internal storage should use a generic CacheEntry<T> interface with fields value: T and expiresAt: number. Write a demo that stores a User object (id and name) and a string, retrieves them before and after expiry using setTimeout. Estimated time: 20 minutes.
Mini Project
Generic REST API Client
Build a typed REST API client class ApiClient<T>. The class stores a baseUrl string. Implement get(path: string): Promise<T>, post(path: string, body: unknown): Promise<T>, put(path: string, body: unknown): Promise<T>, and delete(path: string): Promise<void>. Each method wraps fetch and parses the JSON response as T. Add a typed ApiError class with status: number and message: string that is thrown when response.ok is false. Create two typed clients: UserClient = new ApiClient<User>('/api/users') and PostClient = new ApiClient<Post>('/api/posts') with appropriate interfaces. Write a demo function that uses both clients, handles ApiError with a type-narrowed catch block, and logs the results.
