Sub topic 4
Narrowing a Union with `typeof`, `in`, and Equality Checks
Assume you know basic TypeScript syntax, type annotations, object types, type aliases, and function parameter and return types. This chapter focuses on the working model for narrowing unions and the mistakes that commonly prevent safe access to union members.
The working model
A union type describes a value that can have one of several types. TypeScript permits only operations that are valid for every member until the code proves which member it has.
function formatId(id: string | number): string {
if (typeof id === "string") {
return id.toUpperCase();
}
return id.toFixed(0);
}
console.log(formatId("ab-12")); // AB-12
console.log(formatId(42.7)); // 43Before the if, id is string | number. Calling toUpperCase immediately would be an error because numbers do not have that method. The typeof check narrows id to string inside the first branch. TypeScript knows that the remaining branch contains a number.
The primitive results supported by typeof include "string", "number", "boolean", "bigint", "symbol", "undefined", and "function". For objects, typeof value usually returns "object", so it does not distinguish one object shape from another.
Narrowing object unions with `in`
When object types have different properties, use the in operator. It checks whether a property exists on a value.
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`;
}
describe({ name: "Milo", meow: () => console.log("meow") });
describe({ name: "Rex", bark: () => console.log("woof") });Both union members have name, so pet.name is available before narrowing. Only Cat has meow, and only Dog has bark. Checking "meow" in pet narrows the true branch to Cat. TypeScript can infer that the remaining branch is Dog.
Narrowing with equality
Equality checks narrow values when the compared value is specific enough.
function describeStatus(
status: "ready" | "loading" | "failed"
): string {
if (status === "ready") {
return "The data is available";
}
if (status === "loading") {
return "The data is being fetched";
}
return "The request failed";
}
console.log(describeStatus("ready"));The first comparison narrows status to "ready". After that branch returns, the second comparison narrows it to "loading" when true. The final statement can treat it as "failed" because the other literal possibilities have already been removed.
Equality can also narrow two variables together. If a and b share a union of possible literal values, a === b tells TypeScript that both variables have the same value in that branch.
Common errors
- Calling a member-specific method before narrowing.
- Using
typeof value === "object"as if it identified a particular object shape. - Checking a property whose name exists on every union member. That check does not separate the members.
- Assuming a truthiness check distinguishes all cases. An empty string,
0, andfalseare valid values but are falsy. - Forgetting that
"property" in valuechecks property presence, not whether the property contains a truthy value.
The following diagram shows the general flow.
When a union grows, revisit every narrowing check. A guard that was sufficient for two members may be incomplete after a third member is added.
Exercise
What is the narrowed type of value inside the if branch, and why? function size(value: string | number): number { if (typeof value === "number") { return value; } return value.length; }
Show answer
Inside the if branch, value is number because typeof value === "number" proves that member. After the branch, it is string, so length is safe.