Sub topic 3
Writing Your Own Type Guards with Type Predicates
Prerequisites: you should know union types, functions, and basic if statements. A type guard is a function that checks a value at runtime and tells TypeScript its type.
User-Defined Type Guards
A type predicate uses the form value is Type as a function's return type. If the function returns true, TypeScript narrows the value.
type ApiUser = {
id: number;
name: string;
};
function isApiUser(value: unknown): value is ApiUser {
return (
typeof value === "object" &&
value !== null &&
"id" in value &&
"name" in value &&
typeof value.id === "number" &&
typeof value.name === "string"
);
}
function show(input: unknown): string {
return isApiUser(input) ? input.name : "not a user";
}The compiler trusts the predicate's implementation. If the function returns true incorrectly, later code can fail at runtime. Check every required property.
Narrowing `unknown` Values
Use unknown for data whose shape you do not yet trust, such as parsed JSON from an external service. Narrow it before reading properties.
const input: unknown = JSON.parse('{"id": 7, "name": "Ada"}');
if (isApiUser(input)) {
console.log(input.name.toUpperCase());
}The guard validates the object before property access.
Assertion Functions
An assertion function throws when a check fails. Its return type uses asserts value is Type.
function assertIsString(value: unknown): asserts value is string {
if (typeof value !== "string") {
throw new TypeError("Expected a string");
}
}
function shout(input: unknown): string {
assertIsString(input);
return input.toUpperCase();
}After the call, TypeScript treats input as a string.
Guards with `filter`
A predicate callback lets filter produce a narrowed array.
const values: (string | null)[] = ["a", null, "b"];
const strings: string[] = values.filter(
(value): value is string => value !== null
);When Narrowing Is Lost
Narrowing may not remain safe across callbacks when a value can be mutated. Copy a property into a const before using it asynchronously.
function scheduleLog(user: { name?: string }): void {
const name = user.name;
if (name !== undefined) {
setTimeout(() => console.log(name.toUpperCase()), 0);
}
}The const alias cannot be reassigned, so the narrowed type remains reliable.
Exercise
Why does isApiUser(input) allow access to input.name?
Show answer
Its value is ApiUser predicate tells TypeScript that a true result means the value has the ApiUser shape.