Generic interfaces, type aliases, and classes

Intermediate · 6 min

Putting type parameters on interfaces, type aliases, and classes, so reusable shapes like `Result<T>` and `Queue<T>` keep their contents typed.

Before thisWhy generics, and generic functionsGeneric constraintsType aliases vs interfaces

Jack Herrington · 6 min

Generic interfaces, type aliases, and classes

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Jack HerringtonReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Interfaces and type aliases take type parameters the same way functions do, which turns a shape like `{ value: T }` into a template that is filled in where the type is used.
  • A generic type is not a type until it receives its arguments: `Box<number>` is a type, `Box` on its own is an error unless every parameter has a default.
  • Type aliases can make any type expression generic, including unions like `Result<T, E>`, tuples, and function types, which interfaces cannot express directly.
  • `type Identity = <T>(value: T) => T` describes one generic function, while `type IdentityOf<T> = (value: T) => T` is a family of ordinary functions, one per `T`.
  • A generic class declares its type parameters after the class name; every instance fixes them once, either explicitly with `new Queue<number>()` or by inference from the constructor arguments.
  • Static members belong to the class itself, not to an instance, so they cannot use the class's type parameters.

From generic functions to generic shapes

Generic functions keep a relationship between a call’s inputs and its output. Data has the same need. A box that holds a value, an API result that holds a payload, a queue that holds jobs: each is one shape that should work for many contents, and each should remember what it holds. Writing NumberBox, StringBox, and UserBox by hand repeats the shape for each. Typing the contents as unknown forgets them.

You already use generic types every day. Array<string> (the long form of string[]), Map<string, number>, and Promise<User> are all generic interfaces from the standard library. This lesson is about writing your own.

Generic interfaces

Put the type parameter after the interface name:

interface Box<T> {
  value: T;
}

const count: Box<number> = { value: 1 };

const bad: Box = { value: 1 };
// Error: Generic type 'Box<T>' requires 1 type argument(s).

A generic interface is like a form with a blank in it. Box is the form; Box<number> is the form with the blank filled. Notice that TypeScript doesn’t infer type arguments for annotations: unlike a function call, there are no arguments to infer from. You write them out, or you give the parameter a default.

Interfaces can combine type parameters with constraints, and they can describe methods that use them:

interface Repository<T> {
  get(id: string): T | undefined;
  save(item: T): void;
}

Generic type aliases

A type alias takes parameters the same way, and it can make any type expression generic, not just an object shape. That is where aliases pull ahead of interfaces:

type Result<T, E = Error> =
  | { ok: true; value: T }
  | { ok: false; error: E };

type Pair<T> = [T, T];
type Mapper<T, U> = (item: T) => U;

function parsePort(raw: string): Result<number> {
  const n = Number(raw);
  return Number.isInteger(n)
    ? { ok: true, value: n }
    : { ok: false, error: new Error(`bad port: ${raw}`) };
}

Result is a union, which an interface can’t be. It’s also a pattern worth keeping: a function that can fail returns Result<number>, and callers check ok before they reach for value, which is ordinary discriminated-union narrowing.

Where the angle brackets go

Function types have two places a type parameter can sit, and they mean different things:

type Identity = <T>(value: T) => T;
type IdentityOf<T> = (value: T) => T;

const id1: Identity = (v) => v; // works for any T, chosen per call
const id2: IdentityOf<string> = (v) => v; // only ever strings

Identity is the type of a generic function: whoever holds one can call it with a number now and a string later. IdentityOf<T> is a generic type that produces a plain function type once you pick T. Ask who chooses the type: the caller at each call, or whoever writes the annotation. Callback types in libraries are usually the second kind; utility functions passed around as values are often the first.

Generic classes

Classes take type parameters after the class name, and every member can use them:

class Queue<T> {
  private items: T[] = [];

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

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

  get size(): number {
    return this.items.length;
  }
}

const jobs = new Queue<number>();
jobs.enqueue(1);
jobs.enqueue("two");
// Error: Argument of type 'string' is not assignable to parameter of type 'number'.

Each instance fixes T once. You can write it explicitly, as above, or let the constructor infer it:

class Cell<T> {
  value: T;

  constructor(value: T) {
    this.value = value;
  }

  map<U>(fn: (value: T) => U): Cell<U> {
    return new Cell(fn(this.value));
  }
}

const text = new Cell("42"); // Cell<string>
const num = text.map(Number); // Cell<number>

map shows that a method can add its own type parameter on top of the class’s. T belongs to the instance; U is chosen per call.

A class can implement a generic interface, passing its own parameter through and adding a constraint:

class MemoryRepository<T extends { id: string }> implements Repository<T> {
  private items = new Map<string, T>();

  get(id: string): T | undefined {
    return this.items.get(id);
  }

  save(item: T): void {
    this.items.set(item.id, item);
  }
}

One restriction: static members can’t use the class’s type parameters. class Registry<T> { static fallback: T; } fails with “Static members cannot reference class type parameters.” There’s only one class object, shared by every Registry<string> and Registry<number>, so there is no single T for a static to refer to.

About the video

Jack Herrington’s short episode from his No BS TS series takes an ordinary class and makes it generic, first over the value it stores and then over its key type as well, so you watch the type parameters thread through the constructor and methods. It’s an episode in a series and picks up a little from the one before it, but the class-generics idea stands on its own. It focuses on classes, so generic interfaces, generic type aliases like Result<T, E>, and the two placements of type parameters on function types are carried by the sections above. Hitesh Choudhary’s longer walkthrough in the links recaps generic functions and constraints before reaching a class example.

Check yourself

  1. 01Why is `const b: Box = { value: 1 };` an error when `interface Box<T> { value: T }` exists?

    `Box` is generic, and a generic type needs its type arguments before it describes any values. TypeScript doesn't infer arguments for type annotations, so you must write `Box<number>`, unless the interface gives `T` a default.

  2. 02What is the difference between `type Identity = <T>(value: T) => T` and `type IdentityOf<T> = (value: T) => T`?

    The first is the type of a generic function: a value of that type works with any `T`, chosen fresh at each call. The second is a generic type alias that produces a non-generic function type once you pick `T`, so `IdentityOf<string>` only accepts and returns strings.

  3. 03Why would you write `Result<T, E>` as a type alias rather than an interface?

    `Result` is a union of a success shape and a failure shape, and only type aliases can name a union. Interfaces describe one object shape, so they can be generic too, but they cannot be a union.

  4. 04Why does `class Registry<T> { static fallback: T; }` fail?

    A static member is shared by the class as a whole, and there is only one class no matter how many `Registry<string>` or `Registry<number>` instances exist. There is no single `T` for the static member to use, so TypeScript forbids it.

  5. 05How does `new Cell("42")` know that `T` is `string` when no type argument was written?

    The constructor's parameter is typed `T`, so the constructor call is an inference site just like a generic function call. The argument `"42"` makes `T` `string`, and that choice is fixed for the life of that instance.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark