Sikau

TypeScript · Day 16 · about 25 min

Generic types

Boxes, results and reusable shapes.

Types with parameters

You've used generic types already: Array<string>, Promise<number>. You can write your own — like a Result type that's either success with data or failure with an error, for any data.

Generic type aliases and interfaces

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

function parseAge(text: string): Result<number> {
  const n = Number(text);
  return Number.isInteger(n) && n >= 0 ? { ok: true, value: n } : { ok: false, error: `"${text}" isn't an age` };
}

const r = parseAge("21");
if (r.ok) console.log(r.value + 1);
else console.log(r.error);

interface Page<Item> {
  items: Item[];
  next: number | null;
}
const page: Page<string> = { items: ["a", "b"], next: 2 };

The rest of this lesson

  • Generic types you already knowexplain
  • Result: errors as valuesexplain
  • Valid?predict
  • Reading a Resultpredict
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 24 lessons of TypeScript