Sub topic 4
Narrowing a Union with typeof, in, and Equality Checks
Prerequisites
This chapter assumes you can declare a union such as string | number, you know which members are accessible on a union before narrowing, and you are comfortable with type aliases and function signatures. If a union still feels unfamiliar, review the earlier chapters on union basics and common members first.
What narrowing is
A union type tells the compiler that a value is one of several types. Before you check anything, the compiler only lets you use what every member supports. Narrowing is the process where the compiler refines a union to a smaller set of types inside a branch of code, based on a check you wrote.
The compiler does this with control flow analysis. It reads your if, switch, return, and throw statements and tracks the type of each variable at every point in the function. You do not write a cast. You write ordinary JavaScript checks, and the compiler treats them as evidence.
function formatId(id: string | number): string {
if (typeof id === "string") {
return id.toUpperCase();
}
return id.toFixed(0);
}Inside the if block, id is string. After the block returns, the compiler knows the string case is gone, so id is number for the remaining lines. The check does two jobs: it narrows the true branch and it removes that member from the false branch.
Narrowing with typeof
The typeof operator returns one of eight strings: "string", "number", "bigint", "boolean", "symbol", "undefined", "object", and "function". The compiler recognizes comparisons of typeof x against these literals and narrows x accordingly.
typeof works well for unions of primitives. Here it handles a common input shape: a value that may be missing, a single string, or a list.
function toList(input: string | string[] | null | undefined): string[] {
if (input == null) {
return [];
}
if (typeof input === "string") {
return input.split(",").map((part) => part.trim());
}
return input;
}
console.log(toList("a, b, c")); // ["a", "b", "c"]
console.log(toList(["x"])); // ["x"]
console.log(toList(undefined)); // []Each check removes members. After input == null, the type is string | string[]. After the typeof check returns, only string[] is left.
The typeof null gotcha
In JavaScript, typeof null is "object". The compiler models this, so a typeof x === "object" check does not exclude null.
function size(x: string | string[] | null): number {
if (typeof x === "object") {
// x is string[] | null here, not string[]
return x === null ? 0 : x.length;
}
return x.length; // x is string here
}If you write x.length directly inside the typeof x === "object" branch, the compiler reports that x is possibly null. That error is correct, and it reflects what would happen at runtime.
typeof cannot tell object types apart
typeof returns "object" for arrays, plain objects, dates, and class instances alike. If your union holds several object types, typeof cannot separate them. Use the in operator, a discriminant property, or instanceof for those cases.
Narrowing with equality checks
Comparing a value with ===, !==, ==, or != also narrows. The comparison works in three ways.
Against a literal. If the union contains literal types, comparing to one literal keeps only that member in the true branch and removes it from the false branch.
type Status = "idle" | "loading" | "done";
function label(s: Status): string {
if (s === "idle") {
return "Waiting";
}
// s is "loading" | "done" here
return s === "loading" ? "Working" : "Finished";
}Against another variable. If two values are equal, they must share a type. The compiler narrows both to the types they have in common.
function sameString(a: string | number, b: string | boolean): void {
if (a === b) {
// a and b are both string here
console.log(a.toUpperCase(), b.toUpperCase());
}
}Against null or undefined. Strict equality removes exactly the value you compare against. Loose equality with null removes both null and undefined.
| Check | True branch keeps | False branch keeps |
|---|---|---|
| `x === null` | `null` | everything except `null` |
| `x === undefined` | `undefined` | everything except `undefined` |
| `x == null` | `null` and `undefined` | everything except both |
| `x != null` | everything except both | `null` and `undefined` |
Loose == null is the one place where many style guides allow ==, because it covers both missing values in one check.
Truthiness checks
A bare if (x) also narrows, because it removes null, undefined, false, 0, "", and NaN. This is convenient but easy to get wrong.
function greet(name: string | undefined): string {
if (name) {
return `Hello, ${name}`;
}
return "Hello, stranger";
}This compiles, but an empty string "" also takes the second path. If an empty string is a valid input, use name !== undefined instead.
Narrowing with the in operator
The in operator checks whether a property name exists on an object. It is the tool for unions of object types that typeof cannot separate.
type Cat = { name: string; meow(): void };
type Dog = { name: string; bark(): void };
function describe(pet: Cat | Dog): string {
if ("meow" in pet) {
pet.meow();
return `${pet.name} is a cat`;
}
pet.bark();
return `${pet.name} is a dog`;
}Only name is common to both types, so it is the only member you can read before narrowing. The check "meow" in pet keeps the members that have a meow property in the true branch. The members without it go to the false branch, so pet is Dog after the if.
Rules and edge cases for in
- The property name must be a string literal or a literal-typed value. The compiler cannot narrow on a name it cannot see.
- An optional property stays in both branches. If
Guestdeclaresexpires?: Date, then"expires" in valuekeepsGuestin the true branch (the property might exist) and also in the false branch (it might not). intests presence, not value. An object{ meow: undefined }passes"meow" in pet. If you need to test the value, compare it withundefinedinstead.inalso looks at the prototype chain. The operator returnstruefor inherited properties, such as"toString" in {}. For plain data objects this rarely matters, but it can surprise you with class instances.- Properties not declared in any member. Since TypeScript 4.9, checking a property that no union member declares narrows the value to its type intersected with
Record<"prop", unknown>. You can then read the property asunknown.
Narrowing on assignment
Assigning a value also narrows. The declared type stays wide, but the compiler remembers what you assigned.
let value: string | number = "hello";
console.log(value.toUpperCase()); // allowed: value is string here
value = 42;
console.log(value.toFixed(1)); // allowed: value is number hereBecause narrowing follows the flow of the code, a later assignment replaces the earlier narrowed type.
Combining checks and returning early
Real functions combine several checks. A reliable pattern is to handle the cases you want to remove first and return early, so the rest of the function works on a smaller type.
type Input = string | number | boolean | null;
function describeInput(input: Input): string {
if (input === null) {
return "nothing";
}
if (typeof input === "boolean") {
return input ? "yes" : "no";
}
if (typeof input === "number") {
return input.toFixed(2);
}
return input.trim(); // input is string
}Each check peels one member off the union. The final line works because only string is left. This is easier to read than nested if blocks, and a type error appears if you later add a new member and forget to handle it in a way that breaks the last line.
The compiler also understands &&, ||, !, and the conditional operator ? :, so these narrow as you would expect.
function lengthOrZero(x: string | null): number {
return x !== null && x.length > 0 ? x.length : 0;
}On the right side of &&, x is already string.
Common errors
- Using
typeof x === "object"and forgettingnull. The branch still includesnull. Check fornullfirst or inside the branch. - Truthiness checks on values that can be
0or"". These values are removed from the true branch even though they are valid. Compare explicitly instead. - Narrowing a property, then calling code that might change it. Narrowing on
obj.fieldholds until the next assignment in the same function. Copy the value into aconstif you need the narrowed type inside a callback. - Expecting
into narrow on a computed name. If the property name is a plainstringvariable, the compiler cannot narrow. Use a literal. - Misspelling the
typeofstring.typeof x === "string "or"strng"is reported as an error because the compiler knows the eight valid results.
Choosing a check
| Union members | Best check | Column |
|---|---|---|
| Primitives such as `string \ | number` | `typeof` |
| `null` or `undefined` mixed with other types | `=== null`, `=== undefined`, or `== null` | |
| String or number literals | `===` against a literal, or a `switch` | |
| Object types with different property names | `in` | |
| Object types with a shared literal property | Equality on that property |
Exercise
Given function f(x: string | string[] | null), what is the type of x inside if (typeof x === "object") { ... }, and how do you safely read x.length there?
Show answer
Inside the block, x is string[] | null, because typeof null is "object". Check for null before reading the length, for example x === null ? 0 : x.length, or test x !== null first.
Exercise
Write a function area(shape: { radius: number } | { width: number; height: number }): number that narrows with in and returns the area of a circle or rectangle. What does the compiler do in the else path?
Show answer
Use if ("radius" in shape) { return Math.PI * shape.radius ** 2; } and then return shape.width * shape.height;. In the true branch shape is { radius: number }. After the if returns, the compiler removes that member, so shape is { width: number; height: number } and width and height are accessible.
Exercise
Why does function g(name: string | undefined) { if (name) { ... } } handle "" differently from if (name !== undefined), and which should you use when an empty string is valid?
Show answer
A truthiness check removes "" along with undefined, so the block is skipped for an empty string. name !== undefined removes only undefined, so an empty string still enters the block. Use name !== undefined when an empty string is a valid value.