Sub topic 12
Assertion Functions in TypeScript
Prerequisites and purpose
This chapter assumes you know basic TypeScript functions, union types, unknown, and ordinary if statements. An assertion function is a function whose return type tells TypeScript that a condition is true after the function returns. The function usually throws an error when the condition is false.
Assertion functions are useful when invalid data should stop the current operation. They are common at boundaries such as API responses, configuration loading, and command-line input.
A normal boolean check gives information only inside its own branch:
function isString(value: unknown): boolean {
return typeof value === "string";
}
function shout(input: unknown): string {
if (!isString(input)) {
throw new TypeError("Expected a string");
}
// TypeScript still sees input as unknown here.
return (input as string).toUpperCase();
}The type assertion is needed because TypeScript cannot know what isString checked. An assertion function connects the check to the type system.
`asserts value is Type`
The syntax asserts value is Type means that the named value has the specified type after a successful call.
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();
}
console.log(shout("hello"));Before the call, input has type unknown. If assertIsString returns, TypeScript treats input as a string. If the value is not a string, the function throws and shout does not continue.
The implementation must perform a complete check. TypeScript trusts the declared predicate. It does not verify that the function body really proves the type.
A useful assertion for an object might check both the object itself and each property:
type ApiUser = {
id: number;
name: string;
};
function assertIsApiUser(value: unknown): asserts value is ApiUser {
if (typeof value !== "object" || value === null) {
throw new TypeError("Expected an object");
}
if (!("id" in value) || typeof value.id !== "number") {
throw new TypeError("Expected a numeric id");
}
if (!("name" in value) || typeof value.name !== "string") {
throw new TypeError("Expected a string name");
}
}
function displayUser(value: unknown): string {
assertIsApiUser(value);
return `${value.id}: ${value.name}`;
}
console.log(displayUser({ id: 7, name: "Mina" }));The in checks prove that the properties exist before their values are inspected. This makes the function safe for values received from JSON or another untyped source.
`asserts condition`
An assertion function can also assert an ordinary condition. Its return type uses asserts condition without naming a type.
function assert(condition: unknown, message: string): asserts condition {
if (!condition) {
throw new Error(message);
}
}
function percentage(part: number, whole: number): number {
assert(whole !== 0, "The whole value cannot be zero");
return (part / whole) * 100;
}
console.log(percentage(25, 100));After the call, TypeScript knows that whole !== 0 is true for control-flow analysis. This form is useful for preconditions, such as checking ranges, object state, or required configuration.
Keep assertion functions focused. A function that validates a value should throw a clear error and should not silently return an invalid result.
Exercise
What does TypeScript know about input after assertIsString(input) returns in a function where input has type unknown?
Show answer
TypeScript narrows input to string, because the function's return type is asserts input is string.