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
Syntax
function f(x: unknown): asserts x is T
Examples
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
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
| Version | Change |
|---|---|
| TypeScript 3.7 | Added |
Related
type predicates (x is T)· A function returning 'value is Type' tells TypeScript that the value has that type wherever the function returns true.NonNullable<Type>· Remove null and undefined from a type, for values you've already checked or that can never be missing.- TypeScript keyof, typeof and Indexed Access · tutorial