Sub topic 12
Narrow types with checks and type guards
This chapter assumes you have already renamed a file to .ts, added parameter and return annotations, and turned on strictNullChecks. If string | undefined or User | null still looks unfamiliar, review the chapter on handling null and undefined first.
After a conversion you will often see errors like Object is possibly 'undefined' or Property 'length' does not exist on type 'string | number'. In most cases the fix is not a cast. It is a runtime check that tells the compiler which member of a union you are holding. This is called narrowing.
What narrowing is
A union type such as string | number says a value could be either. TypeScript tracks the type of each variable through the control flow of your function. Inside an if branch that proves the value is a string, the compiler treats it as string. Outside that branch, it goes back to the union.
The checks you already wrote in JavaScript usually count as narrowing. Converting a file often means you only need to move or tighten them so the compiler can see them.
Built-in narrowing checks
TypeScript recognizes these forms without any extra declarations.
| Check | Narrows | Example |
|---|---|---|
| `typeof x === "string"` | Primitives: string, number, boolean, bigint, symbol, undefined, function | `typeof id === "number"` |
| Truthiness: `if (x)` | Removes `null`, `undefined`, `0`, `""`, `false` | `if (user) { ... }` |
| Equality: `x === y`, `x !== undefined` | Removes the compared type | `if (name !== undefined)` |
| `x instanceof Class` | Class instances | `err instanceof Error` |
| `"key" in obj` | Object unions with different properties | `"radius" in shape` |
| `Array.isArray(x)` | Arrays versus other types | `Array.isArray(input)` |
| Discriminant property | Tagged unions | `shape.kind === "circle"` |
typeof and equality
A common JavaScript pattern accepts either a single value or a list. Narrowing with typeof makes it type-safe.
function toIds(input: string | number | number[]): number[] {
if (typeof input === "string") {
return [Number(input)];
}
if (typeof input === "number") {
return [input];
}
return input;
}After the two if blocks return, the compiler knows only number[] is left. You did not need to write a third check.
Truthiness and its trap
Truthiness checks are short, but they also remove 0, "" and false. That is a frequent source of bugs after conversion.
function describePort(port: number | undefined): string {
if (port) {
return "port " + port;
}
return "no port";
}
console.log(describePort(0));The call prints no port, even though 0 is a valid number. If 0 is a legal value, compare directly: if (port !== undefined). The compiler accepts both forms, so it will not warn you about the difference.
The in operator and discriminated unions
When a union contains object types, the in operator checks for a property. A more reliable design gives each member a literal kind field. The compiler then narrows on that field.
interface Circle {
kind: "circle";
radius: number;
}
interface Rectangle {
kind: "rectangle";
width: number;
height: number;
}
type Shape = Circle | Rectangle;
function area(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "rectangle":
return shape.width * shape.height;
}
}Inside each case, shape is the matching interface. If you later add a third shape and forget to handle it, the function no longer returns a number on every path, and the compiler reports an error. That is a useful property when you are converting a large switch statement.
Narrowing the result of find
The find example from the earlier chapters shows the standard pattern. The method returns User | undefined, and an if check narrows it.
interface User {
name: string;
age: number;
}
function findUser(users: User[], name: string): User | undefined {
return users.find((u) => u.name === name);
}
const user = findUser([{ name: "Ada", age: 36 }], "Ada");
if (user) {
console.log(user.name.toUpperCase());
}Without the if, user.name produces an error under strictNullChecks. Prefer this to the non-null assertion user!.name, which silences the error but still throws at runtime if the value is missing.
Where narrowing is lost
Narrowing applies to the current flow of code. It does not always survive these situations:
- Callbacks. A narrowed
letvariable that is reassigned later reverts to its declared type inside a callback, because the compiler cannot know when the callback runs. Copy the value into aconstfirst. - Property access on mutable objects. After
if (obj.value !== undefined), a function call such asreset(obj)may invalidate that check. TypeScript is lenient here and keeps the narrowing, so be careful. - Function boundaries. A check inside a helper function does not narrow the caller's variable unless the helper is a type guard.
function schedule(label: string | undefined): void {
if (label === undefined) {
return;
}
const safeLabel = label;
setTimeout(() => {
console.log(safeLabel.toUpperCase());
}, 10);
}
schedule("backup");Custom type guards
When a check lives in a helper function, tell the compiler what it proves with a type predicate. The return type value is User means that if the function returns true, the argument is a User.
interface 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 loadUsers(text: string): User[] {
const data: unknown = JSON.parse(text);
if (!Array.isArray(data)) {
throw new Error("Expected an array");
}
return data.filter(isUser);
}
console.log(loadUsers('[{"name":"Ada","age":36},{"name":1}]'));The call prints only the valid entry, [ { name: 'Ada', age: 36 } ]. Passing isUser to filter also gives the result the type User[].
The compiler trusts your predicate
A type predicate is a promise. TypeScript does not check that the body matches the claim. If isUser returned true for every object, the code would compile and then fail later. Keep guards small, test them, and check every property the interface requires. If you add a field to User, update the guard in the same change.
Assertion functions
A function can also narrow by throwing. The asserts form is useful for validation code that you would otherwise repeat.
function assertDefined<T>(value: T | undefined | null, label: string): asserts value is T {
if (value === undefined || value === null) {
throw new Error(label + " is required");
}
}
function connect(host: string | undefined): string {
assertDefined(host, "host");
return "connecting to " + host.toLowerCase();
}
console.log(connect("EXAMPLE.COM"));After the assertDefined call, host is a string. Assertion functions must be declared with an explicit type annotation or as function declarations. An arrow function assigned to an untyped const will not work as an assertion.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Valid `0` or `""` treated as missing | Truthiness check | Compare with `undefined` or `null` explicitly |
| Variable is a union again inside a callback | Reassigned `let` | Copy into a `const` before the callback |
| `in` does not narrow | Union members share the property | Add a literal `kind` field |
| Guard compiles but data is wrong | Incomplete predicate body | Check every required property |
| Error on `catch (e)` access | `e` is `unknown` under `useUnknownInCatchVariables` | Check `e instanceof Error` first |
Exercises
Exercise
A converted function has the signature function total(items: number[] | undefined): number and the body return items.reduce((a, b) => a + b, 0);. The compiler reports that items is possibly undefined. Write a fix that returns 0 for a missing list and explain why it is better than items!.
Show answer
Use an early return: if (items === undefined) { return 0; } followed by return items.reduce((a, b) => a + b, 0);. The check narrows items to number[] for the rest of the function, and it handles the missing case at runtime. items! only silences the compiler, so a missing list would still throw a TypeError.
Exercise
You write function isString(x: unknown): boolean { return typeof x === "string"; } and then call if (isString(v)) { v.toUpperCase(); } where v is unknown. Why does this fail, and what is the one-line change?
Show answer
A return type of boolean tells the compiler nothing about the argument, so v stays unknown. Change the signature to function isString(x: unknown): x is string. The compiler then narrows v to string inside the if block.