AI Hints
Home›Angular Tutorial›Classes, Optional and Union Types and Arrays and Generics
Angular · Lesson 14 of 120

Optional and Union Types

Maybe, and one of several.

⏱ 2 min read▶ Video at 16:39🎓 Free
Watch this lesson in the Angular courseWatch on YouTube ↗Full Angular course

Real data is messy. Some books have a subtitle, and some don't. And an id might be a number, or a code. TypeScript can describe all of that.

  • Some values are optional
  • Some can be one of several
  • TypeScript describes both

Optional properties

A question mark makes subtitle optional. So a book may have one, or not. Inside full title, we check for a subtitle, before using it. Run it. Dune has no subtitle. Sapiens shows its subtitle too.

main.tstypescript
interface Book {
  title: string;
  subtitle?: string;
}

function fullTitle(book: Book): string {
  if (book.subtitle) {
    return `${book.title}: ${book.subtitle}`;
  }
  return book.title;
}

console.log(fullTitle({ title: "Dune" }));
console.log(fullTitle({ title: "Sapiens", subtitle: "A Brief History of Humankind" }));
Output
Dune
Sapiens: A Brief History of Humankind
Also uses _mode
ts

Union types

A vertical bar means, or. Number, or string, accepts either one. A union of exact strings, like paperback, or hardback, or ebook, allows only those words. And type gives the union a name, so we can reuse it.

keyvalue
number | stringeither one
"paperback" | "ebook"only these words
type Format = ...a reusable name
typeofcheck which one it is

Unions in action

Format can only be one of three words. Show accepts a number, or a string. Type of tells us which one we have, and TypeScript then allows the right methods. Run it. Ebooks ship free. And each id is shown its own way.

main.tstypescript
type Format = "paperback" | "hardback" | "ebook";

function shipping(format: Format): number {
  return format === "ebook" ? 0 : 2.99;
}

function show(id: number | string) {
  if (typeof id === "number") {
    console.log(`Book number ${id.toFixed(0)}`);
  } else {
    console.log(`Book code ${id.toUpperCase()}`);
  }
}

console.log(shipping("ebook"), shipping("hardback"));
show(42);
show("isbn-0441013597");
Output
0 2.99
Book number 42
Book code ISBN-0441013597
Also uses _mode
ts

A word that is not allowed

Audiobook isn't one of the formats. Run it. TypeScript rejects it, because audiobook is not a Format.

main.tstypescript
type Format = "paperback" | "hardback" | "ebook";

function shipping(format: Format): number {
  return format === "ebook" ? 0 : 2.99;
}

console.log(shipping("audiobook"));
Output
main.ts(7,22): error TS2345: Argument of type '"audiobook"' is not assignable to
parameter of type 'Format'.
Also uses _mode
ts

Summary

A question mark makes a property optional. A vertical bar makes a union, and type of tells the cases apart. Next, arrays, and generics.

Key takeaways
  • subtitle?: string
  • number | string
  • type Format
Next up: Arrays and Generics — lists of things