Skip to content
jshacks.dev
TypeScript

Assertion Functions and the asserts Keyword

An assertion function throws when a check fails and narrows the type when it returns. Learn asserts value is T, asserts condition and the declaration rules.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the TypeScript, Vite, Node.js and JavaScript logos.

A type guard answers a question with a boolean, and you branch on the answer. Sometimes there is no useful second branch. If a configuration value is missing, the program cannot continue, so the honest response is to throw. TypeScript has a signature for that case: an assertion function, declared with the asserts keyword. When it returns normally, the compiler treats the check as passed and narrows the type for every line that follows. This post covers both forms, asserts value is T and asserts condition, the declaration rule that trips people up, how they differ from guards and type assertions, and how to test them. It uses TypeScript 6.x, and the feature is described in the release notes for TypeScript 3.7.

The shape of an assertion function

An assertion function has two parts that must agree: a body that throws when the condition fails, and a return type that tells the compiler what a normal return means.

assert-string.tsTypeScript
function assertIsString(value: unknown): asserts value is string {
  if (typeof value !== "string") {
    throw new TypeError(`Expected a string, received ${typeof value}`);
  }
}

function shout(input: unknown): string {
  assertIsString(input);
  return input.toUpperCase();
}

console.log(shout("ready"));

try {
  shout(42);
} catch (error) {
  if (error instanceof Error) {
    console.log(`${error.name}: ${error.message}`);
  }
}
Text
READY
TypeError: Expected a string, received number

After the call to assertIsString(input), the type of input is string for the rest of the function. No if is needed, and no variable is reassigned. The reason this is sound is the control flow: the only way execution reaches the next line is if the function returned, and it returns only when the check passed. The compiler reads the signature as a promise about the code that follows the call.

Remove the assertion and the same function fails to compile.

without-assert.tsTypeScript
function shout(input: unknown): string {
  return input.toUpperCase();
}
Text
without-assert.ts(2,10): error TS18046: 'input' is of type 'unknown'.

The error is the one a guard would also resolve. The difference is the shape of the code. With a guard you write if (!isString(input)) throw ... yourself at every call site. With an assertion function the throw lives in one place and the call site is a single line.

The asserts condition form

The second form has no type in it. The signature asserts condition says that the argument was truthy if the function returned. It is how you write your own version of the assert function that Node.js ships in node:assert.

assert-condition.tsTypeScript
function assert(condition: unknown, message: string): asserts condition {
  if (!condition) {
    throw new Error(message);
  }
}

type User = { name: string; email?: string };

function mailTo(user: User): string {
  assert(user.email !== undefined, "user has no email");
  return `mailto:${user.email.toLowerCase()}`;
}

console.log(mailTo({ name: "Ada", email: "[email protected]" }));

try {
  mailTo({ name: "Grace" });
} catch (error) {
  if (error instanceof Error) {
    console.log(error.message);
  }
}
Text
mailto:[email protected]
user has no email

The argument is an expression, and the compiler narrows through it. After assert(user.email !== undefined, ...), the property user.email is string and not string | undefined, so toLowerCase is allowed. Any expression the compiler can narrow works here: a typeof test, an in test, a comparison with a literal. The built-in assert from node:assert is declared in the same way in the Node.js type definitions, which is why calling it narrows.

A guard and an assertion compared

Both features turn a runtime check into type information. They differ in what happens when the check fails.

FeatureSignatureOn failureUse when
Type guardvalue is Treturns false, you branchboth outcomes are valid paths
Assertion functionasserts value is Tthrows, execution stopsthe failing path is an error

Pick by the program, not by taste. Parsing user input is a guard case, since invalid input is expected and you want to report it. Reading a required environment variable is an assertion case, since a missing value is a deployment bug and there is nothing to branch to. An assertion function also keeps the happy path flat. Four required values checked by four guards would nest or repeat the throw. Four assertion calls read as four lines.

The declaration rule

Assertion functions come with a restriction that surprises people. Every name in the call target must have an explicit type annotation. A function declaration satisfies this, because its signature is the annotation. An arrow function stored in a const does not, because its type is inferred.

arrow-assert.tsTypeScript
const assertDefined = <T>(value: T | undefined): asserts value is T => {
  if (value === undefined) {
    throw new Error("value is undefined");
  }
};

function run(name: string | undefined): string {
  assertDefined(name);
  return name.trim();
}
Text
arrow-assert.ts(8,3): error TS2775: Assertions require every name in the call target to be declared with an explicit type annotation.

The compiler needs to know at the call site that the callee is an assertion function, and it will not resolve that through inference, because inference itself depends on control flow analysis and the two would be circular. The fix is a function declaration, or an explicit type for the constant.

typed-assert.tsTypeScript
type AssertDefined = <T>(value: T | undefined) => asserts value is T;

const assertDefined: AssertDefined = (value) => {
  if (value === undefined) {
    throw new Error("value is undefined");
  }
};

function run(name: string | undefined): string {
  assertDefined(name);
  return name.trim();
}

console.log(run("  Ada  "));
Text
Ada

The same rule applies to methods. Calling this.validate() or config.assertReady() works when the class or interface declares the method with an asserts signature, since the type is written down. The call is rejected when the object's type is inferred from an object literal that holds an arrow function. Prefer a declared function or method unless you have a reason to hold the assertion in a variable.

A generic non-null assertion

The most common assertion function is the one that removes undefined or null. It replaces the postfix ! operator, which silently trusts you, with a real check that explains itself.

non-null.tsTypeScript
function assertPresent<T>(
  value: T | null | undefined,
  label: string,
): asserts value is T {
  if (value === null || value === undefined) {
    throw new Error(`Missing required value: ${label}`);
  }
}

const env: Record<string, string | undefined> = { PORT: "8080" };

const port = env["PORT"];
assertPresent(port, "PORT");
console.log(Number(port) + 1);

const host = env["HOST"];
try {
  assertPresent(host, "HOST");
} catch (error) {
  if (error instanceof Error) {
    console.log(error.message);
  }
}
Text
8081
Missing required value: HOST

After the first call, port is a string and Number(port) needs no assertion. The failing case produces a message that names the missing value, which is what you want to read in a log at startup. Compare that with the ! operator, which would let undefined flow into Number(...) and print NaN somewhere far from the cause.

What an assertion function cannot promise

The signature is a claim the compiler never checks against the body, exactly as with a type predicate. A function declared as asserts value is string whose body forgets to throw compiles cleanly and narrows the type with no justification.

lying-assert.tsTypeScript
function assertIsNumber(value: unknown): asserts value is number {
  // forgot to throw
}

function double(input: unknown): number {
  assertIsNumber(input);
  return input * 2;
}

console.log(double("four"));
Text
NaN

The program compiles and prints NaN, because the string never failed any check. This is the main risk of the feature, and the remedy is the same as for guards: keep assertion functions small and test them with a case that must throw. If the check is long, call a separate type guard inside the assertion so the logic is written once.

shared-check.tsTypeScript
type Port = number;

function isPort(value: unknown): value is Port {
  return Number.isInteger(value) && (value as number) > 0 && (value as number) < 65536;
}

function assertPort(value: unknown): asserts value is Port {
  if (!isPort(value)) {
    throw new RangeError(`Invalid port: ${String(value)}`);
  }
}

try {
  assertPort(70000);
} catch (error) {
  if (error instanceof RangeError) {
    console.log(error.message);
  }
}
Text
Invalid port: 70000

A guard and an assertion built on one check can never disagree, and callers choose the one that fits their flow.

Testing assertion functions

An assertion function has two behaviours worth pinning: it returns for good input, and it throws a useful error for bad input. The test should check both, and should check the message, since the message is the product.

assert-port.test.tsTypeScript
import { throws, doesNotThrow } from "node:assert/strict";
import { assertPort } from "./shared-check.js";

doesNotThrow(() => assertPort(8080));
throws(() => assertPort(0), { name: "RangeError", message: "Invalid port: 0" });
throws(() => assertPort("80"), { message: "Invalid port: 80" });

console.log("assertion cases passed");
Text
assertion cases passed

Type-level behaviour deserves a test too, since narrowing is the point. A short file that uses the narrowed value, compiled in your normal type check, fails to build if someone weakens the signature to void.

When not to use one

Do not use an assertion function where a failing check should be handled, since an exception is a heavy way to report an expected condition such as invalid form input. Do not use it for data that is validated across many fields, where a schema library gives a typed result and a full list of problems rather than the first one. And avoid exporting a family of assertion functions with inferred types, because of the declaration rule above. They belong at the edges: configuration, environment variables, and the first line of a function that has preconditions.

Share

Keep reading

Flat illustration of two options weighed side by side, with the TypeScript, Node.js, npm and JavaScript logos.
TypeScript

Type Annotations vs Type Assertions

A type annotation asks the compiler to check a value, while an assertion tells it to trust you. Learn the difference, the errors and safer alternatives.

6 min read
Flat illustration of an editor window full of code, with the TypeScript, npm and Node.js logos.
TypeScript

Type Inference in TypeScript

TypeScript works out most types for you. Learn how inference treats let and const, arrays, return values and callbacks, and when to write a type yourself.

7 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.