Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 96 ยท Generics

Generic Interfaces, Classes and Types

Build reusable TypeScript types with generics - Box<T>, generic interfaces and aliases, Result types, generic classes like Stack<T> and Repository<T>, and a typed EventEmitter.

Generic functions are only half the story. The types themselves can take type parameters too: Array<T>, Map<K, V> and Promise<T> are generic interfaces, and you can write your own. A generic type is a type with blanks in it, such as "a box of something" or "a list of something", that you fill in when you use it: Box<number>, List<User>.

In this lesson you'll write generic interfaces and type aliases, model success and failure with a generic Result type, build generic classes (Stack<T>, a Repository<T> for any entity with an ID), learn why static members can't use the class's type parameter, and finish with a fully typed EventEmitter<Events> where every event name knows its payload. It builds on Generics and Generic Constraints and Defaults.

Generic interfaces

Add type parameters after an interface's name, and use them inside like any type:

TypeScript Box and Pair as generic interfaces

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Box<T> is an interface with one type parameter, and its map method has its own second parameter U. This combination is everywhere in real libraries: the container's type is fixed when you create it (T), and each method call can introduce a new type (U). Inside box(), the arrow function for map doesn't need annotations, because its type comes from the Box<T> return type (contextual typing).

Unlike a generic function, a generic type must be given its type arguments when you write it in an annotation, unless its parameters have defaults:

TypeScript A generic type needs its arguments (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TEXT
main.ts(5,10): error TS2314: Generic type 'Box<T>' requires 1 type argument(s).

Generic type aliases

type aliases can be generic too, and since aliases can name unions, they're the natural choice for types like "a value or nothing" and "success or failure". A Result type turns errors into ordinary values that the compiler forces callers to handle:

TypeScript A generic Result type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Result<T, E = Error> has a default for its error type, so Result<number> means Result<number, Error>. Checking result.ok narrows the union, so result.value is only reachable on success and result.error only on failure; this is a discriminated union. The helpers return Result<T, never> and Result<never, E>, which fit any Result with the matching other half, because never is assignable to every type.

Interface or alias? Use a generic interface for object shapes that other code may extend (interface Repository<T>). Use a generic alias when the type is a union, a function type, a tuple, or computed from other types (type Result<T, E>, type Mapper<T, U> = (x: T) => U). The Interfaces lesson has the full comparison.

Generic classes

A class can take type parameters after its name. Fields, constructor parameters and methods may all use them. The classic example is a stack:

TypeScript A generic Stack class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

new Stack<number>() needs an explicit type argument, because an empty constructor gives nothing to infer from. Without it, T would become unknown, and pop() would return unknown. When the constructor does take a T, inference works as it does for functions: new Box('hi') with class Box<T> { constructor(public value: T) {} } gives a Box<string>.

Static members can't use T

A class's type parameter belongs to each instance: one stack holds numbers, another strings. Static members live on the class itself, which is shared by all instances, so there's no single T they could refer to:

TypeScript Static members and type parameters (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TEXT
main.ts(2,23): error TS2302: Static members cannot reference class type parameters.

If a static method needs a type parameter, give the method its own: static of<U>(...items: U[]): Stack<U>.

A generic Repository

Generic classes shine for infrastructure code that works the same for many entity types. This in-memory repository works for any type with an id, and the ID type itself is a second type parameter with a default:

TypeScript Repository of T with a constrained ID

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The constraint T extends Entity<Id> guarantees item.id exists and has the right type. Partial<Omit<T, 'id'>> describes "any subset of the fields except id", built from two utility types. The spread in update produces a type TypeScript treats as compatible with T, so no cast is needed. The same class serves products keyed by numbers and customers keyed by strings, and each repository rejects the other's IDs.

A typed EventEmitter

The final example shows how much a generic type can describe. An event map, an object type from event names to payload types, drives every method:

TypeScript EventEmitter with a typed event map

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

When you call shop.on('cart:add', ...), E is inferred as the literal 'cart:add', so the listener's parameter has the type ShopEvents['cart:add'], and destructuring { sku, quantity } is fully checked. The private field uses a mapped type ({ [E in keyof Events]?: ... }) to store one listener set per event. Adding a new event means adding one line to ShopEvents; every on and emit call is then checked against it. You'll build a fuller version with once and off in Project: Type-Safe Event Emitter.

ShopEvents is declared with type, not interface, on purpose. An object type alias is assignable to Record<string, unknown>, but an interface isn't, because interfaces can be extended later by declaration merging, so TypeScript won't assume they have no other keys. With interface ShopEvents, the line new EventEmitter<ShopEvents>() fails with error TS2344: Type 'ShopEvents' does not satisfy the constraint 'Record<string, unknown>'. If you want to accept interfaces too, constrain the parameter as Events extends object instead.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given interface Box<T> { value: T }, does const b: Box = { value: 1 }; compile?

    Generic types in annotations need their type arguments unless the parameters have defaults. Write Box<number>.
  2. 2. What is the type of r in const r: Result<string> = ... with type Result<T, E = Error> = ...?

    The default for E applies when the argument is omitted, so Result<string> is Result<string, Error>.
  3. 3. Why does class C<T> { static x: T; } fail?

    TypeScript reports TS2302. Give a static method its own type parameter instead.
  4. 4. What is the element type returned by new Stack().pop() if Stack is class Stack<T> and you write no type argument?

    An empty constructor gives nothing to infer, so T becomes unknown, and unknown | undefined is simply unknown. Write new Stack<number>().
  5. 5. In the EventEmitter example, what makes the listener for 'cart:add' receive a typed payload?

    The method's own type parameter E captures the event name, and the indexed access type Events[E] looks up its payload.

Summary

  • Interfaces, type aliases and classes can all take type parameters: interface Box<T>, type Result<T, E = Error>, class Stack<T>.
  • A generic type in an annotation needs its type arguments (TS2314) unless they have defaults; methods may add their own type parameters, like map<U>.
  • Use generic interfaces for extendable object shapes and generic aliases for unions, tuples, function types and computed types.
  • Class type parameters belong to instances; static members can't use them (TS2302). Give empty constructors an explicit type argument.
  • Constraints such as T extends Entity<Id> let generic classes like Repository rely on members, and indexed access (Events[E]) lets one type map drive a whole API, like the typed EventEmitter.

Next: keyof, typeof and Indexed Access Types