Course outline · 0% complete

0/26 lessons0%

Course overview →

Generic Interfaces and Types

lesson 6-2 · ~10 min · 19/26

Shapes with a type slot

Containers are everywhere in real code: a list of users, a box holding a cached value, a result wrapping either data or an error. The container's structure is identical no matter what sits inside, so writing one interface per content type would be the same duplication problem generics just solved for functions. Interfaces (Unit 3) can take type parameters too:

interface Box<T> {
  value: T;
}

const numberBox: Box<number> = { value: 7 };
const wordBox: Box<string> = { value: "hi" };

One interface, many concrete shapes. You have used this all course without noticing: number[] is sugar for the generic Array<number>, and the Pair, Result, and Response types in real codebases are generic interfaces.

Generic functions and generic interfaces compose naturally:

function unwrap<T>(box: Box<T>): T {
  return box.value;
}

Pass a Box<number> and you get a number back, guaranteed.

Code exercise · typescript

Run it. unwrap keeps the connection between what goes in and what comes out. Try unwrap(wordBox) * 2 to see the string version rejected.

Quiz

What is the relationship between number[] and Array<number>?

Code exercise · typescript

Your turn. Define interface Pair<A, B> with first: A and second: B. Write swap<A, B>(p: Pair<A, B>): Pair<B, A> that returns the flipped pair. Create entry: Pair<string, number> = { first: "score", second: 42 }, flip it, and print both as shown.