TypeScript ยท Chapter 21 of 44

TypeScript Generics

Generics let you write reusable functions, classes, and types that work with a variety of types while still preserving type information. Instead of hardcoding one specific type, you use a placeholder like `T`.

When a generic function is called, TypeScript infers or you specify the actual type to use for `T`, and it enforces that type consistently everywhere the placeholder appears.

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

Generic functions

You write a generic function using angle brackets, like `function identity<T>(value: T): T { return value; }`. TypeScript infers T from the argument you pass in.

Generic constraints

You can restrict what types are allowed for a generic parameter using `extends`, ensuring the placeholder type has certain required properties.

Example 1 (typescript)
function identity<T>(value: T): T {
  return value;
}
console.log(identity<number>(5));
console.log(identity("hello"));
Output
5
hello

T adapts to whatever type is passed in, while still preserving type safety.

Example 2 (typescript)
function firstElement<T>(arr: T[]): T {
  return arr[0];
}
console.log(firstElement([1, 2, 3]));
console.log(firstElement(["a", "b"]));
Output
1
a

The generic function works with arrays of any type and returns the correct element type.

Key points

  • Generics use a placeholder type, commonly named T, in angle brackets.
  • TypeScript can infer the generic type from arguments automatically.
  • Generics keep code reusable without losing type safety.
  • Generic constraints use `extends` to require certain properties.
๐Ÿ’ก Note: Generics are one of TypeScript's most powerful features for building flexible, reusable, and type-safe code.

๐Ÿ“ Quick Quiz

1. What symbol is used to declare a generic type parameter?

2. What is the benefit of generics?

3. How can you restrict which types a generic accepts?