lecture 8 of 120 completed

Union and literal types

A union type lists the kinds of value a name may hold. With literal types, it lists the exact values, so a misspelled status no longer compiles.

What you'll learn

  • What a union type is, and how to use a value that has one
  • How a literal type limits a value to a few exact strings
  • Why a value in a variable can lose its literal type

A Shelf test counts the returned loans. One status in the test data is misspelled.

interface Loan {
  book: string;
  status: string;
}

const loans: Loan[] = [
  { book: "Dune", status: "returned" },
  { book: "Emma", status: "retuned" },
];

console.log(loans.filter((loan) => loan.status === "returned").length);
1

The compiler reports nothing, and the count is 1 where the test author meant 2. The type string accepts every text, and "retuned" is text.

A status is not any text. It is one of a few known words, and TypeScript can say that.

Literal types and unions

A literal type is a type with exactly one value. The type "returned" accepts the text "returned" and nothing else.

One value alone is not useful. A union type joins several types with |, which you read as "or".

type LoanStatus = "on-loan" | "returned" | "overdue";

interface Loan {
  book: string;
  status: LoanStatus;
}

const loan: Loan = { book: "Emma", status: "retuned" };
loans.ts(8,36): error TS2820: Type '"retuned"' is not assignable to type 'LoanStatus'. Did you mean '"returned"'?

type LoanStatus = ... gives the union a name, so every file can use it. A name made with type is called a type alias. Now a status must be one of three exact words, and the misspelled one is an error at the place it was written.

Your editor also benefits. It offers the three words when you type the opening quote.

Unions of other types

A union can join any types. You already used one: an optional field is string | undefined.

Here a library card id may be text or a number.

function cardLabel(id: string | number): string {
  return id.toUpperCase();
}
cards.ts(2,13): error TS2339: Property 'toUpperCase' does not exist on type 'string | number'.
  Property 'toUpperCase' does not exist on type 'number'.

Read the last line first, as in lecture 5. A number has no toUpperCase. With a union, the compiler allows only what works for every member.

To do more, check which member you have. TypeScript follows the check, as it did for undefined.

function cardLabel(id: string | number): string {
  if (typeof id === "string") {
    return id.toUpperCase();
  }
  return "CARD-" + id;
}

console.log(cardLabel("a-17"));
console.log(cardLabel(17));
A-17
CARD-17

Inside the if, id is text. After it, only the number is left.

A variable can lose the literal type

Many people are surprised by this the first time.

type LoanStatus = "on-loan" | "returned" | "overdue";

function countByStatus(status: LoanStatus): number {
  return 0;
}

let wanted = "returned";
countByStatus(wanted);
loans.ts(8,15): error TS2345: Argument of type 'string' is not assignable to parameter of type 'LoanStatus'.

"returned" is one of the three words, and the call is still refused. The reason is let. A let variable can be given another value later, so TypeScript infers the wide type string for it. Then a string does not fit LoanStatus.

There are two fixes. Use const, because a const can never change and keeps the exact type. Or annotate the variable, so the compiler checks every value you put in it.

type LoanStatus = "on-loan" | "returned" | "overdue";

function countByStatus(status: LoanStatus): number {
  return 0;
}

const fixed = "returned";
let changing: LoanStatus = "returned";

countByStatus(fixed);
countByStatus(changing);

Where you will meet this

Test frameworks use unions of literals for their own options. In Playwright, the role you pass to getByRole is one, so a misspelled role does not compile. Your own code has the same kind of values: user roles, order statuses, the names of test environments.

When a value comes from a small fixed set, type it as a union of literals. A typing mistake in test data then fails in the compiler. With string, it becomes a filter that matches nothing, as in the first example.

Remember this

A union type says "one of these". A union of literal types limits a value to a few exact strings. To use one member of a union, check for it first. A let variable holds the wide type string unless you annotate it.

Reference: Union Types in the TypeScript Handbook.

now prove it

Reading is the setup. Solve this exercise in the editor. We check your code with the TypeScript compiler and list each type error.