Demo mode — data resets on refresh.

Functions and Generics

Generics

What are Generics?

Generics let you write reusable code that works with multiple types while retaining type safety. Think of them as type variables.

function identity<T>(arg: T): T { return arg }

The T is a type parameter. When you call identity("hello"), TypeScript infers T as string.

Generic Constraints

You can constrain what types a generic can accept using extends.

function getLength<T extends { length: number }>(arg: T): number { return arg.length }

Generic Interfaces and Classes

Interfaces and classes can also be generic, making them incredibly flexible building blocks.

Knowledge Check

1.What symbol is typically used for a generic type parameter?

2.What does a generic constraint (extends) do?