Generic functions & constraints (extends, default params)
Create generic functions, add constraints with extends, and use default type parameters for ergonomic APIs.
Intro
Goal: Make functions reusable and type-safe with generics. You will define type parameters, add extends constraints, and set default type params for better DX.
Identity generic
Define a type parameter <T>. The compiler infers T from arguments, so callers rarely annotate it.
function identity<T>(x: T): T {
return x;
}
const a = identity(42); // T inferred as number
const b = identity("ts"); // T inferred as string
console.log(a, b);All lessons in this course
- Generic functions & constraints (extends, default params)
- Partial, Readonly, Record, Pick, Omit
- keyof/indexed access types (intro)