Warm-up1 / 1
Can you write this from memory?
Write a generic identity function that takes type T and returns T
TypeScript generics let you write functions and types that work with any type while keeping full type safety. They're the foundation of reusable TypeScript code -- and the syntax trips people up more than the concept does.
This page covers the core patterns. For a full reference with copy-ready examples, see the generics cheat sheet.
What You'll Practice: TypeScript Generics: Constraints, Defaults & Patterns
Write generic functions with type parametersConstrain generics with extendsUse keyof with generic constraints for safe property accessSet default type parametersApply conditional types with infer
TypeScript Generics: Constraints, Defaults & Patterns Sample Exercises
Example 1Difficulty: 1/5
Fill in the generic type parameter
<T>Example 2Difficulty: 2/5
Write generic function `first` that returns the first element of any array (or undefined if empty)
function first<T>(items: T[]): T | undefined { return items[0]; }Example 3Difficulty: 2/5
Constrain T to objects with a length property (number type)
extends { length: number }+ 3 more exercises
Quick Reference
TypeScript Generics: Constraints, Defaults & Patterns Cheat Sheet →Copy-ready syntax examples for quick lookup