TypeScript · module 8 of 21
Generics
Generics let you write reusable code that works with different types while staying type-safe. They use the <T> syntax.
What this module covers
4 steps · TypeScript
Step 1. Generics
Generics let you write reusable code that works with different types while staying type-safe. They use the <T> syntax. function getFirst<T>(arr: T[]): T { return arr[0]; } getFirst<number>([1, 2, 3]); // 1 getFirst<string>(["a", "b"]); // "a" interface ApiResponse<T> { data: T; success: boolean; message: string; } Generics let you write flexible, reusable functions, interfaces, and classes while maintaining strong type safety across every use, and can add constraints (T extends ...) to require certain properties on the generic type.
Generics avoid writing near-duplicate functions for every type — one definition, type safety preserved for every call site. In TypeScript, make the state/interaction visible in the UI so completion is easy to verify.
Check yourself: [TypeScript] Call the identity function with two different types.
Step 2. Quiz: Generics
Answer these questions about generics.
<T> marks a generic type parameter; TypeScript can usually infer it from the arguments passed in. In TypeScript, make the state/interaction visible in the UI so completion is easy to verify.
Check yourself: [TypeScript] Answer the quiz below.
Step 3. Write a Generic Function
Write a generic function called wrapInArray that takes a value of type T and returns T[]. Call it at least twice with different types.
This is the smallest possible generic function, but the pattern — take a T, return something built from T — is the shape most generic utilities follow. In TypeScript, make the state/interaction visible in the UI so completion is easy to verify.
Check yourself: [TypeScript] Does wrapInArray use <T>, take T, return T[], and get called with two different types?
Step 4. Mini project: Generics
Write a generic function called wrapInArray that takes a value of type T and returns T[]. Call it at least twice with different types. Turn the completed challenge into a small standalone project. Add realistic content, clear naming, one edge case or error state, and a short README-style explanation of how the main idea works.
This is the smallest possible generic function, but the pattern — take a T, return something built from T — is the shape most generic utilities follow. This project stage asks you to apply the same idea without step-by-step scaffolding. In TypeScript, make the state/interaction visible in the UI so completion is easy to verify.
Check yourself: [TypeScript] Does wrapInArray use <T>, take T, return T[], and get called with two different types?
Loading code lab...