Union and literal types
Combining types with `|`, using exact values like `"GET"` as types, and the widening rules that decide when TypeScript keeps a literal.
Union and literal types
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- A union type `A | B` accepts a value of either type; on its own, it only lets you use what both members have in common.
- A literal type is a single exact value used as a type, such as `"GET"`, `404`, or `true`; on its own it is narrow, and in a union it becomes a precise set of allowed values.
- A union of string literals, like `"GET" | "POST"`, replaces a loose `string` with a closed list, so typos and unsupported values fail to compile and editors can autocomplete the options.
- `boolean` is just the union `true | false`.
- Literals widen: `let` and object properties infer `string` rather than `"GET"` because they can change later, so passing them where a literal union is required needs an annotation or `as const`.
Real values come in more than one shape
So far every variable has had one type. Real data doesn’t always cooperate. An ID might be a number from the database or a string from a URL. A function might return a result or an error. An HTTP method is a string, but not just any string: "GTE" is a bug. Two features handle these cases: unions say “one of several types”, and literal types say “exactly this value”. Together they describe data far more precisely than primitives alone.
Union types
A union joins types with |:
let id: string | number;
id = 42; // fine
id = "a1b2"; // fine
id = true; // Error: Type 'boolean' is not assignable to type 'string | number'.
The catch is on the reading side. If a value might be either type, you can only use what both have:
function describe(id: string | number) {
id.toString(); // fine: both have toString
id.toUpperCase(); // Error: Property 'toUpperCase' does not exist on type 'string | number'.
}
That’s the right call. At runtime, id could be 42, and (42).toUpperCase() would crash. To use string-only methods you check which one you have first, with typeof id === "string". That checking, narrowing, is the subject of the next group. This lesson is about building unions; narrowing is about taking them apart.
You’ve already seen unions in passing: string | null in the strict null checks lesson, and (string | number)[] for mixed arrays.
Literal types
Any single string, number, or boolean value can also be used as a type:
let method: "GET" = "GET";
method = "POST"; // Error: Type '"POST"' is not assignable to type '"GET"'.
A type with one value isn’t much use alone. Put several in a union and you have a closed list:
type Method = "GET" | "POST" | "PUT" | "DELETE";
type StatusCode = 200 | 404 | 500;
function request(url: string, method: Method) {
return fetch(url, { method });
}
request("/users", "GET"); // fine
request("/users", "GTE"); // Error: Argument of type '"GTE"' is not assignable to parameter of type 'Method'.
Think of it as a drop-down menu instead of a free-text field. A free-text string accepts anything and leaves validation for later; a literal union offers exactly the valid choices, and the editor autocompletes them as you type. Change the union in one place and every call site using a removed option fails to compile.
boolean is itself the union true | false, which is why you can write a type like { ok: true; data: string } | { ok: false; error: string }. Unions of objects tagged this way are discriminated unions, one of the most useful patterns in the language.
Widening: when a literal stays a literal
TypeScript infers literal types only where it is safe to. The annotations and inference lesson showed the basic rule:
const a = "GET"; // "GET": a const can't change
let b = "GET"; // string: a let could be reassigned to any string
Inferring string for a let is called widening. It also applies to object properties, because they can be reassigned too, and that is where it bites:
type Method = "GET" | "POST";
declare function send(method: Method): void;
const req = { url: "/users", method: "GET" }; // method: string
send(req.method); // Error: Argument of type 'string' is not assignable to parameter of type 'Method'.
req is a const, but that only freezes the binding. req.method could still be set to "banana" later, so TypeScript infers string. There are two clean fixes:
type Method = "GET" | "POST";
declare function send(method: Method): void;
const req1: { url: string; method: Method } = { url: "/users", method: "GET" };
send(req1.method); // fine: the annotation says what method may hold
const req2 = { url: "/users", method: "GET" } as const;
send(req2.method); // fine: method is readonly "GET"
The annotation states the real contract. as const freezes the whole object and keeps every literal, as the readonly lesson showed. Pick the annotation when the object is meant to be a Method-carrying shape, and as const for fixed tables of values.
Literals are subtypes of their primitives
Every "GET" is a string, so a literal type is assignable wherever its primitive is expected. The reverse needs proof: a string isn’t assignable to "GET" | "POST", because it might be anything. This one-directional rule explains nearly every literal-type error you’ll meet.
About the video
developedbyed’s 2024 video covers literal types, unions of literals, and widening with let versus const, which is the core of this lesson. It also strays into narrowing, which this roadmap covers in the next group, so treat that part as a preview. The video shows less of the object-property widening problem, so the req.method example above is worth working through yourself in an editor. Benny Code’s video in the links concentrates on unions of non-literal types if you want more practice there.
Check yourself
Why does `function len(x: string | number) { return x.length; }` fail to compile?
On a union, you can only use members that every type in it has. `string` has `length` but `number` does not, so the compiler reports that `length` doesn't exist on `string | number`. You need to narrow `x` to `string` first.
What does the type `"left" | "right" | "center"` give you that `string` doesn't?
It limits the value to exactly those three strings, so a typo like `"centre"` is a compile error rather than a silent bug, and the editor can suggest the three valid options as you type.
Why does `const req = { method: "GET" }; send(req.method)` fail when `send` takes `"GET" | "POST"`?
Object properties are mutable, so TypeScript widens `method` to `string` when inferring the object's type. A `string` could be any string, so it isn't assignable to the literal union. Annotating the object with the right type, or writing `as const`, keeps the literal.
Is `const port = 8080` typed as `number`?
No, it is typed as the literal `8080`, because a `const` can never be reassigned. It is still assignable anywhere a `number` is expected, since every literal type is a subtype of its primitive.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.