TypeScript 7 reference · Type Operators and Keywords

TypeScript assertion functions (asserts x is T) Keyword

A function declared 'asserts value is Type' throws if the check fails, and narrows the type after the call.

TypeScript 7 Since 3.7

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

function f(x: unknown): asserts x is T

Examples

Narrow by assertingTry it yourself
function assertString(v: unknown): asserts v is string {
  if (typeof v !== "string") throw new Error("expected a string");
}
const input: unknown = "hello";
assertString(input);
console.log(input.toUpperCase()); // narrowed to string

Output

HELLO
Required configurationTry it yourself
function assertDefined<T>(v: T, name: string): asserts v is NonNullable<T> {
  if (v == null) throw new Error(`${name} is required`);
}
try {
  const port: string | undefined = undefined;
  assertDefined(port, "PORT");
} catch (e) {
  console.log((e as Error).message);
}

Output

PORT is required

Version history

VersionChange
TypeScript 3.7Added

Was this page helpful?