Sub topic 9
Literal Types and Unions
This chapter assumes you know basic TypeScript annotations, the difference between const and let, and how typeof checks work in JavaScript. It builds on the inference rules from earlier in the tutorial.
A literal type is a type that allows exactly one value, such as "north" or 42. A union type is a type that allows any one of several types, written with |. Combining them lets you say that a value must be one of a fixed set of options.
Declaring a literal union
type Direction = "north" | "south" | "east" | "west";
let heading: Direction = "north";
heading = "east"; // ok
// heading = "up"; // Error: Type '"up"' is not assignable to type 'Direction'.This catches typos at compile time. A plain string would accept "nroth" without complaint.
Literal widening
When you declare a variable with let and no annotation, TypeScript widens the literal to its primitive type. A const declaration keeps the literal.
let a = "north"; // type: string
const b = "north"; // type: "north"Widening causes a common error in object literals:
const request = { method: "GET" }; // method is widened to string
// send(request); // Error if send expects { method: "GET" | "POST" }Fix it with an annotation on the object, which gives the literal a contextual type:
const request: { method: "GET" | "POST" } = { method: "GET" };Narrowing a union
A union value can only be used in ways that work for every member. Narrowing uses control flow checks to reduce the union to one member.
type Id = number | string;
function format(id: Id): string {
if (typeof id === "number") {
return id.toFixed(0); // id is number here
}
return id.trim(); // id is string here
}Equality checks against literals also narrow, which works well for status values:
type Status = "idle" | "loading" | "done";
function describe(s: Status): string {
switch (s) {
case "idle":
return "Waiting";
case "loading":
return "Working";
case "done":
return "Finished";
default: {
const unreachable: never = s; // compile error if a member is added
return unreachable;
}
}
}If someone later adds "failed" to Status, the never assignment fails. The compiler then points you to the switch that needs a new case.
Diagram
Exercise
Exercise
Given type Size = "small" | "medium" | "large", why does const s = "small" let you pass s to a function that expects Size, but let s = "small" does not?
Show answer
const keeps the literal type "small", which is a member of Size. let widens the declared type to string, which is not assignable to Size. Annotate the variable as Size to fix it: let s: Size = "small";