Module lessons (2/2)
Fundamental Generics
Write generic functions, interfaces, and classes with compile-time safe extends keyof T constraints.
What you'll learn in this lesson
- Understand why
anydestroys the relationship between input and output while Generics (<T>) preserves it. - Let the compiler infer arguments of type
<T>from the values passed to the call. - Apply constraints (
<T extends { length: number }>) andK extends keyof Tto read properties safely. - Parameterize interfaces (
Box<T>,Pair<T, U>,ApiResult<T>) for containers and asynchronous responses.
Overview
Without generics you would have two poor choices: duplicate the same function for string, number and User, or use any losing autocompletion on the return value. A generic type parameter (<T>) captures the actual type provided by the caller and carries it exactly to the result.
Inside a generic function <T>, TypeScript assumes that T can be any type, so it prohibits access to .length or arbitrary properties until you declare a constraint (extends).
Sections covered in this lesson
- 1Generic Functions and Interfaces
- 2Constraints with
extendsandK extends keyof T - 3Guided practice
- 4Check for understanding
Unlock "Fundamental Generics" and the full Course TypeScript curriculum
Write generic functions, interfaces, and classes with compile-time safe extends keyof T constraints.
Unlock all 6 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Course TypeScript plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.