Skip to content

Generic

In one line

A generic is a type variable (like T) that lets you write functions, classes, and types that work with any type while preserving type safety.

In simple words

Generics are type variables. Instead of writing a function for each type, you write one function with a type parameter (usually called T) that the caller specifies. This makes code reusable without sacrificing type safety.

For example, identity<T>(x: T): T works with any type — pass a number, get a number; pass a string, get a string. The type relationship between input and output is preserved, which would be lost if you used any.

Generics are used everywhere in TypeScript: in arrays (Array<T>), in Promises (Promise<T>), in Map (Map<K, V>), and in most utility types. You can constrain generics with extends to limit what types are allowed.

Example

typescript
function identity<T>(value: T): T {
  return value;
}

const num = identity(42);     // T inferred as number
const str = identity("hi");  // T inferred as string

// Constrained generic
function getLength<T extends { length: number }>(x: T): number {
  return x.length;
}

identity works with any type. getLength requires T to have a length property.

Related terms

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary