Advanced TypeScript · 9 min read · Intermediate
Generics & Type Constraints
Write reusable, type-preserving functions and wrappers with <T> and extends constraints.
What you'll learn
- Preserve exact input-to-output types using generic functions (<T>)
- Constrain generic parameters with <T extends { id: string }>
- Use keyof T to index objects with 100% compile-time safety
Generics act like type-level parameters. Instead of losing type information with any, function first<T>(items: T[]): T | undefined remembers whether you passed number[] or User[] and returns the exact matching element type.
Fill-in-the-Blank Exercise
Generic First Helper
Declare a generic type parameter T so first() preserves the element type.
function first<>(items: T[]): T | undefined {
return items[];
}Live Code Lab
TypeScriptgenerics.ts
Expected OutputClick “Run Live” to compile with TypeScript 5.6
First: 95 | Name: TypeScript
Check Your Understanding
Score: 0 / 1
1. What does K extends keyof T constrain in a TypeScript generic function?
Study Workspace
Finished this lesson?
Your progress is saved locally in your browser, no account needed.