Sub topic 1
Why union types need narrowing
Prerequisites
This chapter assumes you can do the following:
- Write basic TypeScript: variables, functions, interfaces, and type aliases.
- Read a union type such as
string | numberand say which values it allows. - Use JavaScript
ifstatements,switchstatements, and the ternary operator. - Run
tscor use an editor that shows TypeScript errors.
All examples assume "strict": true in tsconfig.json. That setting turns on strictNullChecks, which makes null and undefined separate types. Several examples depend on it.
A union only promises what all its members share
A union type says a value is one of several types, and the compiler does not know which one. The compiler therefore lets you use only the operations that are valid for every member.
function format(value: string | number): string {
return value.toUpperCase();
}The compiler rejects this with error TS2339:
Property 'toUpperCase' does not exist on type 'string | number'.
Property 'toUpperCase' does not exist on type 'number'.The error is correct. If a caller passes 42, then value.toUpperCase is undefined, and calling it throws a TypeError at runtime. The compiler stops you before that happens.
Members that both types share are allowed:
function describe(value: string | number): string {
return value.toString();
}Both string and number have toString(), so the call compiles. The set of operations allowed on a union is the intersection of what each member offers. A wider union leaves fewer operations available.
The same rule applies to object unions and null
Objects follow the same rule. Only properties that exist on every member can be accessed directly.
type Fish = { swim(): void };
type Bird = { fly(): void };
function move(animal: Fish | Bird): void {
animal.swim(); // error: Property 'swim' does not exist on type 'Fish | Bird'.
}Optional and nullable values are unions as well. The type string | null is a union of string and null. With strictNullChecks on, this code does not compile:
function length(name: string | null): number {
return name.length; // error: 'name' is possibly 'null'.
}The type T | undefined is the same kind of union. It appears when you declare an optional parameter (name?: string), read an optional property, or index into an array or map that may not have the key. Unions are everywhere in everyday TypeScript, so narrowing is something you do constantly.
Narrowing: proving which member you have
Narrowing is how you tell the compiler which member of a union a value is. You write a check that the compiler understands, and inside the branch guarded by that check, the compiler uses a more specific type.
function format(value: string | number): string {
if (typeof value === "string") {
return value.toUpperCase();
}
return value.toFixed(2);
}Inside the if block, value is string, so toUpperCase() is valid. The block returns, so the code after it can only run when the check failed. There, value is number, and toFixed(2) is valid.
The check is real JavaScript that runs. The compiler reads it and draws a conclusion from it. This matters because TypeScript types are erased when the code is compiled to JavaScript. At runtime there is no string | number, only a value. A narrowing check has to be something JavaScript can evaluate: typeof, instanceof, a property test, a comparison with a constant, or a function you write that does those tests.
Declared type and narrowed type
A variable has one declared type, but the type the compiler uses can change from one line to the next. The compiler follows each path through your code and tracks what is known to be true at every point. This tracking is called control flow analysis, and the next chapter covers it in detail.
Assignment also narrows:
let id: string | number = "abc-123";
console.log(id.toUpperCase()); // ok: id is string here
id = 42;
console.log(id.toFixed(0)); // ok: id is number hereThe declared type of id stays string | number throughout. That is why the second assignment is allowed. At each use, the narrowed type is whatever the last assignment or check established.
flowchart TDThe diagram below shows the same idea for format.
Why not just use a type assertion
A type assertion with as also makes the error go away:
function format(value: string | number): string {
return (value as string).toUpperCase();
}
console.log(format("abc")); // "ABC"
console.log(format(42)); // TypeError at runtimeThis compiles, and format(42) still crashes. An assertion tells the compiler to believe you without checking anything. Narrowing differs because the check runs and the compiler's conclusion follows from it. If the code later changes so that the check no longer proves the claim, the compiler reports an error. An assertion never reports one.
Prefer narrowing whenever a runtime check is possible. Keep as for cases where you know something the compiler cannot verify, and treat each use as a place where a bug could hide.
The tools you will use
Each way of narrowing fits a different kind of union. The following chapters cover them one by one.
| Technique | Good for | Example check |
|---|---|---|
| `typeof` | Primitives such as string, number, boolean | `typeof x === "string"` |
| Truthiness | Removing `null`, `undefined`, `0`, `""` | `if (x) { ... }` |
| Equality | Null checks and comparing to constants | `x == null`, `x === "a"` |
| `in` operator | Object types with different properties | `"swim" in animal` |
| `instanceof` | Class instances such as `Error` | `e instanceof Error` |
| Discriminated union | Objects tagged with a literal property | `shape.kind === "circle"` |
| Type predicate | Custom checks you reuse | `isApiUser(x)` |
Two items on this list do more than the rest. Discriminated unions are the usual design for modelling variants, and the compiler can check that you handled every case. Type predicates let you package a runtime check as a function that the compiler trusts.
Common errors
These mistakes come up often when you first work with unions.
- Reaching for
asfirst. The code compiles, and the bug moves to runtime. Write the check instead. - Checking something TypeScript cannot see at runtime. You cannot write
value instanceof FishwhenFishis a type alias or interface. Only classes exist at runtime. Useinor a discriminant property for plain object types. - Assuming a check on one variable narrows another. Narrowing applies to the expression you tested. Testing
a.kindnarrowsa. It does not narrow a separate variablebthat happens to hold the same value. - Forgetting the branch that remains. With
string | number | boolean, atypeofcheck forstringleavesnumber | booleanin the else path. Narrowing removes members, and what is left may still be a union. - Expecting narrowing to last forever. Narrowing can be lost inside callbacks or after a function call that might change the value. The last chapter of this tutorial covers this.
A worked example with all the pieces
This function accepts a value that may be missing, a number, or a string. It shows several narrowing steps in sequence.
function normalizeId(id: string | number | null | undefined): string {
if (id == null) {
return "unknown";
}
// id is string | number here
if (typeof id === "number") {
return id.toString().padStart(6, "0");
}
// id is string here
return id.trim();
}
console.log(normalizeId(42)); // "000042"
console.log(normalizeId(" abc ")); // "abc"
console.log(normalizeId(null)); // "unknown"Each check removes members from the union. The first removes null and undefined. The second removes number, leaving string. By the last line the compiler knows exactly what id is, and every method call is checked against that type.
You can hover over id in your editor at each line to see the narrowed type. This is a quick way to learn how the compiler reasons, and it helps when narrowing does not work as you expected.
Exercise
The function below fails to compile. Explain why, then fix it without using as.
function double(input: string | number): number {
return input * 2;
}
Show answer
The arithmetic operator * requires number operands, and input might be a string, so the compiler reports an error. Narrow the union first. One fix:
function double(input: string | number): number {
if (typeof input === "string") {
return Number(input) 2;
}
return input 2;
}
Inside the if block input is a string, so it is converted with Number. After the block it is a number.
Exercise
A teammate writes (value as string).toUpperCase() for a parameter typed string | number. The code compiles. What goes wrong when a caller passes 42, and why did the compiler not warn about it?
Show answer
At runtime, (42).toUpperCase is undefined, so calling it throws a TypeError. The compiler did not warn because a type assertion tells it to trust you and performs no check. Narrowing with typeof value === "string" would have made the compiler verify the claim.
Exercise
Why can you not narrow Fish | Bird with animal instanceof Fish when Fish is declared with type Fish = { swim(): void }?
Show answer
instanceof is a JavaScript operator that needs a constructor function at runtime. A type alias is erased during compilation, so no Fish value exists to test against. Use the in operator ("swim" in animal) or add a literal discriminant property to each member.