Sub topic 3
How TypeScript narrows types
This chapter assumes you know basic TypeScript syntax, including type annotations, union types such as string | number, and if and switch statements. It also assumes strict: true in your tsconfig.json. Without strict mode, null and undefined are silently allowed in every type, and several examples below would behave differently.
What narrowing is
A union type says a value could be one of several types. At the point where you use the value, you usually need to know which one it is. Narrowing is how TypeScript refines a variable from its declared type to a more specific type inside a region of code, based on checks you wrote.
function format(value: string | number | null): string {
// value: string | number | null
if (value === null) {
return "none";
}
// value: string | number
if (typeof value === "string") {
return value.toUpperCase(); // value: string
}
return value.toFixed(2); // value: number
}
console.log(format("hi"), format(3), format(null));Each check removes members from the union. After the null check returns, null is gone. After the typeof check returns, string is gone, so only number is left.
Discriminated unions rely on this mechanism. Checking a tag property is one more kind of narrowing check, and it works because of the rules in this chapter.
Control flow analysis
TypeScript does not narrow by pattern-matching on syntax. It performs control flow analysis: it follows every path through your function and tracks the type of each variable at each point. Narrowing is therefore a property of a location in the code, not of the variable itself.
Two consequences follow. First, early returns are a clean way to narrow: code after if (x === null) return sees x without null. Second, where branches merge, the types merge too. After an if/else in which one branch narrows to string and the other to number, the variable is string | number again.
The narrowing checks
TypeScript recognizes a fixed set of checks. The table lists the ones you will use most.
| Check | Narrows by | Typical use |
|---|---|---|
| `typeof x === "string"` | primitive type | `string`, `number`, `boolean`, `bigint`, `symbol`, `undefined`, `function` |
| `x === null`, `x == null` | equality | removing `null` or `undefined` |
| `if (x)` | truthiness | removing `null`, `undefined`, `0`, `""`, `false` |
| `"key" in x` | property presence | choosing between object types |
| `x instanceof C` | class prototype chain | class instances such as `Error` |
| `x.kind === "a"` | discriminant property | discriminated unions |
| `isFoo(x)` | type predicate | custom checks |
typeof and equality
typeof narrows primitives. It has one well-known trap: typeof null is "object", so an object check must also exclude null.
function describe(value: object | null): string {
if (typeof value === "object") {
// value is still object | null here, because typeof null === "object"
return value === null ? "null" : "an object";
}
return "unreachable";
}Equality narrowing works with === and !==. It also works between two variables: if a: string | number and b: string | boolean, then inside if (a === b) both are narrowed to string, the only type they share. The loose form x == null is the one common use of loose equality, because it matches both null and undefined.
Truthiness
An if (x) check removes every falsy member from the type. That includes null and undefined, but also 0, "", NaN, and false. This is convenient for strings and objects, and a bug for numbers.
function lengthOf(text: string | undefined): number {
if (text) {
return text.length; // text: string
}
return 0;
}
function describeCount(count: number | undefined): string {
if (count) {
return `count is ${count}`;
}
return "no count"; // also reached when count is 0
}
console.log(describeCount(0)); // "no count"describeCount(0) reports "no count" even though a count was supplied. When zero or the empty string is a legitimate value, compare explicitly with count !== undefined.
The in operator
The in operator narrows between object types by testing for a property. It suits unions of types that have no shared tag.
type Cat = { meow(): void };
type Dog = { bark(): void };
function speak(pet: Cat | Dog): void {
if ("meow" in pet) {
pet.meow(); // pet: Cat
} else {
pet.bark(); // pet: Dog
}
}
speak({ bark: () => console.log("woof") });This works only while the property names are distinct across members. If both types had meow, the check would not separate them. A dedicated tag property is more reliable, which is the motivation for discriminated unions.
instanceof
instanceof narrows to a class by walking the prototype chain. It is the standard way to handle values caught in catch, since caught values are unknown under strict settings.
function messageOf(error: unknown): string {
if (error instanceof Error) {
return error.message; // error: Error
}
return String(error);
}
try {
JSON.parse("{ not json");
} catch (error) {
console.log(messageOf(error));
}Discriminant property checks
When every member of a union has a property with a literal type, comparing that property narrows the whole object. This is the check the rest of the tutorial builds on. A small example:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number };
function scale(shape: Shape, factor: number): Shape {
if (shape.kind === "circle") {
return { kind: "circle", radius: shape.radius * factor }; // shape: circle member
}
return { kind: "square", size: shape.size * factor }; // shape: square member
}
console.log(scale({ kind: "square", size: 2 }, 3));The check on shape.kind narrows shape itself, not just the property. Inside the if, shape.radius exists. In the remaining code, only the square member is possible.
Assignment narrowing
Assigning a value to a variable narrows it to the type of that value, within the declared type.
let current: string | number = "draft";
current.toUpperCase(); // current: string after the assignment
current = 42;
console.log(current.toFixed(1)); // current: numberThe declared type still limits what you can assign. You can assign only string or number, but TypeScript knows which one the variable holds at each line.
Where narrowing is lost
Narrowing depends on TypeScript being sure that nothing changed the value between the check and the use. Several situations break that certainty.
- Reassignment. Assigning to a variable replaces the narrowed type with the type of the new value, as shown above.
- Callbacks and closures. A function created inside a narrowed region may run later, after the variable has changed. A
constvariable keeps its narrowing inside closures. Forletvariables and parameters, older TypeScript versions drop the narrowing, and TypeScript 5.4 and later keep it only when no assignment follows the closure's creation. - Property access on mutable objects. Narrowing
user.namedoes not survive a function call that could modifyuser. TypeScript does not model side effects, so it keeps the narrowing anyway in many cases, but you should not rely on it across arbitrary calls.
function process(input: string | undefined): void {
const value = input; // const keeps narrowing inside closures
if (value === undefined) return;
[1, 2, 3].forEach((n) => {
console.log(value.length + n); // value: string
});
}
process("abc");When a narrowed property is needed after a call or inside a callback, copy it to a const first. That makes the intent explicit and works in every TypeScript version.
Type predicates
The built-in checks cover many cases, but sometimes the logic is yours. A function with a return type of the form x is T is a type predicate. When it returns true, TypeScript narrows the argument to T at the call site.
function isString(value: unknown): value is string {
return typeof value === "string";
}
const items: unknown[] = ["a", 1, "b", null];
const strings: string[] = items.filter(isString);
console.log(strings); // ["a", "b"]The compiler trusts a predicate without checking its body. If the function returns true for the wrong values, the narrowing is wrong and nothing warns you. A later chapter returns to this when validating external data.
Why this matters for unions
Every technique above works by removing members from a union until one remains. A discriminated union gives that process a reliable tool: a literal-typed property that each member sets differently. The next chapters cover choosing that property and what the compiler can then guarantee.
Exercise
What does describeCount(0) print for the function below, and how would you change the check so that zero is reported as "count is 0"?
function describeCount(count: number | undefined): string {
if (count) {
return count is ${count};
}
return "no count";
}
Show answer
It returns "no count", because if (count) is a truthiness check and 0 is falsy. Replace the condition with if (count !== undefined). That narrows count to number for every number, including 0, and only undefined falls through to "no count".
Exercise
Given function f(x: string | number | null), what is the type of x on the line after if (x == null) return;, and why does == work here when === with only null would not?
Show answer
The type is string | number. The loose comparison x == null is true for both null and undefined, and TypeScript narrows away both. A strict x === null check would remove only null, which is enough for this particular parameter type but would leave undefined in a type such as string | undefined | null.