Lesson 10 / 1283%

Lesson 10

Generics

25 min

Write reusable code that keeps type safety, with T and extends.

What is a generic?

Definition

A generic is a "fill-in-the-blank" type: instead of writing a specific type, you use a type parameter (often written T) whose value will be chosen later, at the time of use. The same code can then work with several types, while keeping the safety of each one.

Think of a labeled box: the box itself doesn't change, but the label says what it contains, books, shoes or tools. Generics work the same way: a single definition, several possible contents, and the editor always knows what is inside.

The problem: repeated code for each type

Imagine a function that returns the first element of an array. For it to work with numbers and strings, you could write two versions, or use any and lose type safety. Generics offer a better solution.

without_generics.ts
function firstNumber(arr: number[]): number {
  return arr[0];
}

function firstString(arr: string[]): string {
  return arr[0];
}
// Same logic, twice...
with_any.ts
function firstAny(arr: any[]): any {
  return arr[0];
}

const x = firstAny([10, 20]);
x.toUpperCase();   // No error... but it crashes at runtime!

The version with any avoids the repetition, but it loses all information: the result no longer has a type, and TypeScript no longer detects the error on the last line. We need a way to say "the result has the same type as the elements of the array", whatever that type is.

A generic function

A generic is a type parameter, written between angle brackets after the function name. By convention, it is named T (for "Type"). TypeScript automatically determines its value from the arguments.

generic.ts
function first<T>(arr: T[]): T {
  return arr[0];
}

const a = first([10, 20, 30]);        // a: number
const b = first(["x", "y", "z"]);     // b: string
const c = first<boolean>([true]);     // type specified by hand
Screenshot of VS Code showing the signature tooltip of a generic function when hovering over its call.

In the first call, TypeScript sees an array of numbers, deduces that T is number, and therefore knows that the result is a number. In the second, T is string. You can also specify T yourself between angle brackets, as in the third call, but inference rarely makes that necessary.

Several type parameters

A function can have as many type parameters as needed. They are then named A, B, or with more meaningful names like Key and Value when that helps.

pair.ts
function createPair<A, B>(first: A, second: B): [A, B] {
  return [first, second];
}

const pair = createPair("Lea", 25); // [string, number]

Generic arrow functions

Arrow functions can also be generic: the angle brackets go right before the parameter parentheses. This notation is very common for small utilities.

generic_arrow.ts
const identity = <T>(value: T): T => value;

const n = identity(42);          // number
const t = identity("text");      // string

In a .tsx file (React), <T> would be mistaken for an HTML tag: you then write <T,> instead. In a regular .ts file, as here, the simple form is enough.

Generic interfaces and classes

Generics also apply to interfaces and classes. A very common case: describing the response of an API whose content varies.

generic_interface.ts
interface ApiResponse<T> {
  success: boolean;
  data: T;
}

interface User {
  name: string;
}

const res1: ApiResponse<User> = {
  success: true,
  data: { name: "Lea" },
};

const res2: ApiResponse<number[]> = {
  success: true,
  data: [1, 2, 3],
};
generic_class.ts
class Stack<T> {
  private items: T[] = [];

  push(item: T): void {
    this.items.push(item);
  }

  pop(): T | undefined {
    return this.items.pop();
  }
}

const stack = new Stack<string>();
stack.push("a");
stack.push(42); // Error: number is not assignable to string

A stack is a structure where the last element added is the first one removed. Thanks to the generic, the same Stack class works for texts, numbers or objects, and each stack stays homogeneous: a Stack<string> rejects anything that isn't a text.

Default values for type parameters

Like function parameters, a type parameter can have a default value, indicated with the equals sign. It is used when no other value is specified.

default.ts
interface Box<T = string> {
  content: T;
}

const b1: Box = { content: "text" };        // T is string
const b2: Box<number> = { content: 42 };    // T is number

Constraining a generic

Sometimes, T can't be just any type: the function needs a specific property. You then limit T with extends.

constraint.ts
function printLength<T extends { length: number }>(item: T): number {
  return item.length;
}

printLength("hello");     // 5
printLength([1, 2, 3]);   // 3
printLength(42);          // Error: number has no length property

The constraint extends { length: number } means: "T can be any type, as long as it has a length property of type number". Texts and arrays qualify, numbers don't. Inside the function, you can then read item.length safely.

Good to know

You already use generics without knowing it: number[]is a shorthand for Array<number>, andPromise<string> describes a promise that will produce a text.

  • Use a generic when the same code must work on several types while keeping the link between input and output.
  • Don't overuse them: if a simple type or a union is enough, it is more readable.

Linking two types with keyof

You can also constrain a type parameter based on another one. The keyof operator produces the union of a type's property names, which lets you write a function that reads a property safely.

keyof.ts
function read<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

const person = { name: "Lea", age: 25 };

const personName = read(person, "name");   // string
const personAge = read(person, "age");     // number
read(person, "email");                     // Error: email does not exist

Here, K can only be "name" or "age", and the return type T[K] automatically adapts to the requested property. A typo in the property name is detected immediately.

Common mistakes

  • Pointless generic: if T appears only once in the signature, it links nothing and a simple type is enough.
  • Falling back to any: a generic keeps the link between input and output, any destroys it.
  • Obscure names: T is fine for a single parameter, but prefer explicit names as soon as there are several.

Generics are one of TypeScript's most powerful tools, but also one of the most intimidating at first. Don't try to write them everywhere: start by using them (arrays, promises, API responses), then write your own when you notice identical code repeated for several types.

Summary

  • A generic is a type parameter, written between angle brackets.
  • TypeScript almost always infers its value from the arguments.
  • Generics apply to functions, interfaces and classes.
  • extends limits the accepted types; the equals sign gives a default value.

Exercise

Write a generic function last<T>(arr: T[]) that returns the last element of an array (or undefined if the array is empty), and test it with numbers and strings.

Going further

Create a generic class Box<T> that stores a value, with the methods get() and replace(value: T).