Sub topic 11
Type Predicates for Narrowing
Assume you know JavaScript functions, callbacks, union types, and basic TypeScript compilation. This chapter focuses on a common problem: checking a value at runtime and having TypeScript understand the result at compile time.
Why ordinary checks are sometimes not enough
Suppose a function receives unknown. The unknown type means that TypeScript does not allow you to use the value until you check what it is.
function formatValue(value: unknown): string {
if (typeof value === "string") {
return value.toUpperCase();
}
if (typeof value === "number") {
return value.toFixed(2);
}
return "Unsupported value";
}TypeScript narrows value inside each branch. After the first check, it treats value as a string. After the second check, it treats it as a number.
When the same check is needed in several places, put it in a type predicate function.
Writing a type predicate
A type predicate is a return type in the form parameterName is Type.
function isString(value: unknown): value is string {
return typeof value === "string";
}
function shout(input: unknown): string {
if (isString(input)) {
return input.toUpperCase();
}
return String(input);
}
console.log(shout("hello")); // HELLO
console.log(shout(42)); // 42The expression value is string tells the compiler that a true result means the argument is a string. The function must return a boolean at runtime, but its special return annotation provides information to the type checker.
The parameter named in the predicate must be a parameter of the function. This is invalid:
// function isString(value: unknown): otherValue is string {
// return typeof value === "string";
// }Narrowing object unions
A predicate can check the shape of an object. Check each required property before using it.
type User = {
kind: "user";
name: string;
};
type ErrorResult = {
kind: "error";
message: string;
};
type Result = User | ErrorResult;
function isUser(result: Result): result is User {
return result.kind === "user" && typeof result.name === "string";
}
function describe(result: Result): string {
if (isUser(result)) {
return `User: ${result.name}`;
}
return `Error: ${result.message}`;
}
console.log(describe({ kind: "user", name: "Ada" }));
console.log(describe({ kind: "error", message: "Not found" }));The predicate connects the runtime test to the compile-time type. In the if branch, result is User. In the remaining branch, TypeScript knows that result is ErrorResult.
Predicates with array methods
Predicates are especially useful with filter. Without a predicate, filtering an array of union values may not produce the specific array type you want.
function isString(value: unknown): value is string {
return typeof value === "string";
}
const values: unknown[] = ["Ada", 7, "Grace", false];
const names: string[] = values.filter(isString);
console.log(names.map(name => name.toUpperCase()));Here, filter uses the predicate to infer string[].
A generic predicate can preserve a relationship between a value and a type parameter:
function isDefined<T>(value: T | undefined): value is T {
return value !== undefined;
}
const optionalNumbers: Array<number | undefined> = [1, undefined, 3];
const numbers: number[] = optionalNumbers.filter(isDefined);
console.log(numbers);How narrowing works
A predicate narrows only where TypeScript can use its result. It does not permanently change the declared type of a variable, validate data for other programs, or replace runtime validation at an external boundary.
Common errors
- Claiming a type without checking all required properties.
- Using
as Userwhen a predicate would provide a checked, reusable rule. - Forgetting that
nullandundefinedneed explicit checks. - Assuming a predicate validates data received from an API unless it checks the complete runtime shape.
- Returning a predicate type that does not match the function's actual boolean result.
Exercise
Write a type predicate named isNumber that accepts unknown, then use it to create a number[] from [1, "2", 3, null].
Show answer
function isNumber(value: unknown): value is number { return typeof value === "number"; } followed by const numbers = [1, "2", 3, null].filter(isNumber);