Sikau

TypeScript · Day 8 · about 20 min

Union types

This or that.

One of several types

An ID might be a number or a string. A setting might be a value or not set. A union type says "this OR that", with a | between the options.

Writing and using unions

function format(id: number | string): string {
  return "#" + id;
}
format(42);
format("A-17");
format(true);

function len(id: number | string) {
  return id.length;
}

The rest of this lesson

  • What you can do with a unionexplain
  • Unions of objectsexplain
  • Is it allowed?predict
  • Read the unionmatch
  • 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