Sub topic 12
Narrow Types with Checks and Type Guards
Assume you know JavaScript functions, objects, arrays, and basic TypeScript annotations. This chapter focuses on narrowing: reducing a broad type to a more specific type after checking its value.
TypeScript often starts with a union type such as string | number. You cannot use every operation on that value immediately. A string has .toUpperCase(), while a number does not. A narrowing check gives TypeScript evidence about which type remains.
Use built-in narrowing checks
The typeof operator narrows primitive values:
function formatId(id: string | number): string {
if (typeof id === "number") {
return `ID-${id.toFixed(0)}`;
}
return id.toUpperCase();
}
console.log(formatId(42));
console.log(formatId("abc"));Inside the if block, TypeScript knows that id is a number. After the block, the only remaining possibility is string.
Equality checks narrow literal values and nullable values:
function printName(name: string | null): void {
if (name === null) {
console.log("No name");
return;
}
console.log(name.toUpperCase());
}The return matters. It removes the null path before name.toUpperCase() runs.
With objects, the in operator checks whether a property exists:
type EmailContact = {
email: string;
};
type PhoneContact = {
phone: string;
};
function describeContact(contact: EmailContact | PhoneContact): string {
if ("email" in contact) {
return `Email: ${contact.email}`;
}
return `Phone: ${contact.phone}`;
}Write a type guard
A type guard is a function whose return type tells TypeScript what a successful check proves. Its return type uses the form value is SomeType.
type User = {
name: string;
age: number;
};
function isUser(value: unknown): value is User {
if (typeof value !== "object" || value === null) {
return false;
}
const record = value as Record<string, unknown>;
return (
typeof record.name === "string" &&
typeof record.age === "number"
);
}
function getUserName(value: unknown): string {
if (isUser(value)) {
return value.name;
}
return "Unknown user";
}
console.log(getUserName({ name: "Ada", age: 36 }));
console.log(getUserName({ name: "Grace" }));The input is unknown, so the function cannot access properties until it checks the value. The isUser guard performs those runtime checks. After isUser(value) returns true, TypeScript treats value as a User.
Common narrowing mistakes
A type assertion does not perform a runtime check:
const user = value as User;This only tells the compiler to trust you. Prefer a real guard when the value came from JSON, a request, or another untyped boundary.
Also check the value before dereferencing it. This is unsafe:
function firstName(users: User[]): string {
return users[0].name;
}The array might be empty. A safer version narrows the result:
function firstName(users: User[]): string | undefined {
const first = users[0];
if (!first) {
return undefined;
}
return first.name;
}Exercise
Why does isUser(value) allow value.name, while value as User does not protect data at runtime?
Show answer
isUser performs runtime checks and reports whether they passed. as User only changes the compiler's view and can hide invalid data.