Sub topic 12
Assertion functions
This chapter assumes you know union types, unknown, and type predicates (value is T) from the earlier chapters. An assertion function is a close relative of a type predicate. It narrows a value for all the code that follows the call, and it does so by throwing an error when the check fails.
What an assertion function does
A type predicate returns a boolean, and you use it in an if. An assertion function returns nothing. If it returns normally, the compiler assumes the check passed. If the check fails, the function must throw.
The narrowing therefore applies to every statement after the call, in the same scope. You don't need an if or an early return.
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"));The return type asserts value is string is the signature. It tells the compiler this: "if this call completes, value is a string." After assertIsString(input), the type of input changes from unknown to string.
Two forms of the signature
TypeScript has two assertion signatures.
| Signature | Meaning | Typical use |
|---|---|---|
| `asserts value is T` | After the call, `value` has type `T`. | Validating `unknown` input |
| `asserts condition` | After the call, `condition` is truthy. | A general `assert(...)` helper |
The second form takes any expression as the condition. The compiler narrows according to whatever that expression would narrow in an if.
function assert(condition: unknown, message: string): asserts condition {
if (!condition) {
throw new Error(message);
}
}
function double(x: number | undefined): number {
assert(x !== undefined, "x is required");
return x * 2;
}
console.log(double(21));The compiler reads assert(x !== undefined, ...) as a promise that x !== undefined holds afterwards. So x is number on the last line.
Node's assert function from node:assert and Vitest's and Jest's expect-style helpers use this same signature. The calls assert(typeof v === "string") and assert.ok(v) narrow v the same way.
Validating parsed data
The most common use is checking data that enters your program from outside, such as JSON.parse, request bodies, or environment variables. Compare the style with a type predicate. A predicate forces you to handle the failing branch at every call site. An assertion function lets you write the validation once and keep the happy path flat.
type Config = { port: number; host: string };
function assertIsConfig(value: unknown): asserts value is Config {
if (
typeof value !== "object" ||
value === null ||
!("port" in value) ||
!("host" in value) ||
typeof value.port !== "number" ||
typeof value.host !== "string"
) {
throw new TypeError("Invalid config");
}
}
const raw: unknown = JSON.parse('{"port": 8080, "host": "localhost"}');
assertIsConfig(raw);
console.log(`${raw.host}:${raw.port}`);JSON.parse returns any by default. Annotating raw as unknown forces the check before use. The in and typeof checks inside the function narrow value step by step, as in the chapter on narrowing unknown.
A reusable non-null helper
Generic assertion functions are useful for removing null and undefined.
function assertDefined<T>(
value: T,
name: string
): asserts value is NonNullable<T> {
if (value === null || value === undefined) {
throw new Error(`${name} must be defined`);
}
}
function readPort(env: Record<string, string | undefined>): number {
const raw = env["PORT"];
assertDefined(raw, "PORT");
return Number.parseInt(raw, 10);
}
console.log(readPort({ PORT: "3000" }));After the call, raw is string, not string | undefined.
Assertion functions on methods: `asserts this`
A method can narrow this. The signature is asserts this is T. This helps with objects that move through states, such as a session that may or may not be logged in.
class Session {
token?: string;
login(token: string): void {
this.token = token;
}
assertLoggedIn(): asserts this is this & { token: string } {
if (this.token === undefined) {
throw new Error("Not logged in");
}
}
}
const session = new Session();
session.login("abc123");
session.assertLoggedIn();
console.log(session.token.length);Without the call to assertLoggedIn(), session.token.length is a compile error because token may be undefined. After the call, session has the intersection type with a required token.
Rules and gotchas
The function name needs an explicit type
The compiler only uses an assertion signature if it can see the signature without inferring it. This is the most common error with assertion functions. A function declaration is fine. A const holding an arrow function is not, because the type of the const is inferred.
// Error TS2775: Assertions require every name in the call target
// to be declared with an explicit type annotation.
const assertIsNumber = (value: unknown): asserts value is number => {
if (typeof value !== "number") {
throw new TypeError("Expected a number");
}
};
function useIt(input: unknown): number {
assertIsNumber(input);
return input;
}There are two fixes. The simpler one is to use a function declaration. The other is to annotate the variable.
const assertIsNumber: (value: unknown) => asserts value is number = (
value
) => {
if (typeof value !== "number") {
throw new TypeError("Expected a number");
}
};
function useIt(input: unknown): number {
assertIsNumber(input);
return input;
}
console.log(useIt(42));The same rule applies to every part of a call target. If you call utils.assertIsNumber(x), then utils must also have an explicit type. An imported namespace or a class instance with a declared type satisfies this. An object literal assigned to an unannotated const does not.
The compiler does not check the body
The compiler trusts your signature. This compiles without complaint and is wrong:
function assertIsStringBroken(value: unknown): asserts value is string {
// No check at all.
}
function risky(input: unknown): string {
assertIsStringBroken(input);
return input.toUpperCase();
}risky(42) compiles and then crashes at runtime with toUpperCase is not a function. A type predicate has the same weakness, so test the function itself. Cover both the accepting and rejecting inputs.
It must throw, not return
An assertion function reports failure only by throwing. If your check function returns false or logs an error, the compiler still believes the narrowing holds. Use an assertion function only when you are willing to abort the current operation on bad input.
Narrowing applies from the call onward
If you call the assertion inside a branch, the narrowing stays in that branch. After the branches merge, the types combine again.
function handle(input: string | number, strict: boolean): void {
if (strict) {
assert(typeof input === "string", "strict mode needs a string");
console.log(input.length);
}
// Here input is string | number again.
}The assert helper is the one defined earlier in this chapter. Its return value is void, so it cannot be used as an expression.
Hoisting and callbacks
Narrowing from an assertion call does not carry into callbacks that run later, for the same reasons given in the chapter on where narrowing is lost. If you need the value inside a callback, copy it into a const after the assertion.
Assertion function or type predicate?
| Question | Type predicate | Assertion function |
|---|---|---|
| How does it report failure? | Returns `false` | Throws |
| Where does narrowing apply? | Inside the `if` branch (and the `else` for the remaining types) | Every statement after the call |
| Best fit | Choosing between alternatives, such as `filter` | Validating input that must be valid to continue |
| Works as a callback for `filter`? | Yes | No, because it returns nothing |
Use a predicate when a failed check is a normal outcome and you have a fallback. Use an assertion function when a failed check means the program cannot continue, as with invalid configuration or a violated internal invariant.
Summary
asserts value is TnarrowsvaluetoTfor all code after the call.asserts conditionnarrows by the truthiness of an expression, which makes it the signature for a generalasserthelper.asserts this is Tnarrowsthisafter a method call.- The call target must have an explicit type annotation, or the compiler reports TS2775.
- The compiler never checks the body, so the check must be complete and must throw on failure.
Exercise
The code below fails to compile with error TS2775. Why does it fail, and what is the smallest change that fixes it? const assertPositive = (n: number): asserts n is number => { if (n <= 0) throw new Error("Not positive"); }; function f(x: number): void { assertPositive(x); }
Show answer
The arrow function is assigned to a const with no type annotation, so its assertion signature is inferred. The compiler requires an explicit type for the call target of an assertion. The smallest fix is to rewrite it as a function declaration: function assertPositive(n: number): asserts n is number { ... }. Annotating the variable with a full function type also works.
Exercise
Write an assertion function assertIsStringArray(value: unknown): asserts value is string[] that throws a TypeError unless value is an array whose elements are all strings. Then show how a caller uses it on the result of JSON.parse.
Show answer
function assertIsStringArray(value: unknown): asserts value is string[] {
if (!Array.isArray(value) || !value.every((v) => typeof v === "string")) {
throw new TypeError("Expected an array of strings");
}
}
const parsed: unknown = JSON.parse('["a", "b"]');
assertIsStringArray(parsed);
console.log(parsed.map((s) => s.toUpperCase()));
After the call, parsed is string[], so map and toUpperCase type-check. The every check is what makes the signature true. Without it the compiler would still accept the code but the claim would be false.