Skip to lesson

TypeScript · Lesson 25 of 42

Generic interfaces, type aliases and classes

Parameterise interfaces, type aliases and classes with type parameters, set default types, and see how Array<T> and Promise<T> are built the same way.

Beginner to advanced·14 min·Generics·Updated 2026-11-24

UNDERSTAND IT. THEN TRY IT.

What you can do after this lesson

You will create types that are templates: a container, a response wrapper, a data structure, each working for any content type while staying fully checked. This extends the idea of generic functions to the types you declare.

Generic interfaces and type aliases

An interface or a type alias can take type parameters in angle brackets after its name:

typescript
interface Box<T> {
  value: T;
}

const numberBox: Box<number> = { value: 42 };
const stringBox: Box<string> = { value: "hello" };

console.log(numberBox.value + 1, stringBox.value.toUpperCase());
result
43 HELLO

Box<T> is a template, and Box<number> fills it in. When you use a generic type, you must give the type argument, and the compiler checks the value against it:

typescript
interface Box<T> {
  value: T;
}

const wrong: Box<number> = { value: "hello" };
result
example.ts(5,30): error TS2322: Type 'string' is not assignable to type 'number'.

Type aliases work the same way. A very common real-world use is a wrapper for API responses:

typescript
type ApiResponse<T> =
  | { status: "ok"; data: T }
  | { status: "error"; message: string };

type User = { id: number; name: string };

function show(response: ApiResponse<User>): string {
  if (response.status === "ok") {
    return `Hello, ${response.data.name}`;
  }
  return `Failed: ${response.message}`;
}

console.log(show({ status: "ok", data: { id: 1, name: "Asha" } }));
console.log(show({ status: "error", message: "not found" }));
result
Hello, Asha
Failed: not found

One definition, ApiResponse<T>, describes the response for users, products or anything else. It is also a discriminated union, so narrowing on status works as in the earlier lesson.

Several parameters and default types

A generic type may have more than one parameter. You can also give a parameter a default, used when the caller does not supply one:

typescript
interface Pair<A, B = A> {
  first: A;
  second: B;
}

const names: Pair<string> = { first: "Asha", second: "Ben" };
const mixed: Pair<string, number> = { first: "age", second: 30 };

console.log(names, mixed);
result
{ first: 'Asha', second: 'Ben' } { first: 'age', second: 30 }

In Pair<string>, B defaults to A, so both are strings. Defaults keep the common case short while allowing flexibility.

Generic classes

A class can take type parameters too. The classic example is a data structure that holds items of one type:

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

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

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

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

const numbers = new Stack<number>();
numbers.push(1);
numbers.push(2);
console.log(numbers.pop(), numbers.size);
result
2 1

Each Stack is created for one type. Pushing the wrong kind of thing is an error:

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

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

const numbers = new Stack<number>();
numbers.push("three");
result
example.ts(10,14): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.

Classes are covered in detail in a later section. For now, notice that the same type parameter T appears throughout the class, tying its methods together.

Constraints on generic types

Type parameters on interfaces and classes can also have constraints with extends, exactly as on functions:

typescript
interface HasName {
  name: string;
}

class Registry<T extends HasName> {
  private items = new Map<string, T>();

  add(item: T): void {
    this.items.set(item.name, item);
  }

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

const registry = new Registry<{ name: string; price: number }>();
registry.add({ name: "pen", price: 2 });
console.log(registry.get("pen")?.price);
result
2

You have used generic types all along

Several types you already know are generic:

  • Array<T> is the long form of T[]. So string[] is Array<string>.
  • Promise<T> describes a value that arrives later (the next sections cover it).
  • Map<K, V> and Set<T> are the built-in collections, as the Registry above used.
  • Record<K, V> describes an object with keys K and values V.

Seeing them as generic types explains why they have angle brackets and why the compiler knows what you get out of them.

Common mistakes

Forgetting the type argument. Box alone is an error when the type parameter has no default. Write Box<number>.

Using generics for a single concrete case. If a type will only ever hold numbers, do not parameterise it.

Confusing the type parameter with a value. T exists only for the compiler. You cannot write new T() or typeof T in the running code.

Giving too many type parameters. Each one makes the type harder to read. Two or three is plenty for most designs.

Exercise

Write interface Result<T, E = string> as a discriminated union with success and failure, and use it for a function that parses an integer. Write class Queue<T> with enqueue, dequeue and a size getter. Create a Queue<string> and a Queue<number>, and try mixing the types to read the error.

Next: keyof, typeof and indexed access types.

KNOWLEDGE CHECK

A quick check. You’ve got this.

Try each question. Every answer comes with an explanation.

0 / 4 understood
01 How do you create a Box that holds a number, given interface Box<T> { value: T }?
02 What does interface Response<T = string> do when you write Response without a type argument?
03 What does Stack<T> in class Stack<T> describe?
04 Is Array<string> the same as string[]?

Ready for the next small win?

Mark the lesson complete when you are ready.

Course navigation

Frontend

TypeScript tutorial

Add types to JavaScript to catch mistakes before your code runs, from your first annotation to generics and real projects.

Your progress 0/42
Learning something new?Explore all courses