TypeScript
Assertion function
Learn assertion functions with asserts.
Assertion function
An assertion function uses a return type of the form asserts x is T. When the function completes normally, TypeScript narrows the parameter to type T; if the condition fails, the function throws. While a type guard returns true/false, an assertion function either narrows or throws.
function assertString(x: unknown): asserts x is string {
if (typeof x !== "string") {
throw new Error("Expected string");
}
}
function upper(v: unknown): string {
assertString(v);
return v.toUpperCase(); // v: string
}
Assert vs is
A type guard with is is a function returning true/false and narrows in an if condition. An assertion function with asserts narrows by completing or throwing; no if needed. Assert is useful when you want to stop execution on error.
// type guard
function isString(x: unknown): x is string {
return typeof x === "string";
}
// assertion function
function assertString(x: unknown): asserts x is string {
if (typeof x !== "string") throw new Error("not string");
}
function upper(v: unknown): string {
assertString(v); // next line: v is string
return v.toUpperCase();
}
Exercise Handle unknown with assertString
Define an assertString(x: unknown): asserts x is string function (with throw new Error("not string") when typeof x !== "string"). Write an upper(v: unknown): string function: first call assertString(v), then return v.toUpperCase(). Print the result via console.log(upper("hello")).
Show example solution
function assertString(x: unknown): asserts x is string {
if (typeof x !== "string") {
throw new Error("not string");
}
}
function upper(v: unknown): string {
assertString(v);
return v.toUpperCase();
}
console.log(upper("hello"));
Test yourself
-
How does a return type of asserts x is T behave?
- It auto-generates the T type
- The function returns true/false
- It does nothing at runtime
- When the function completes it narrows x to T; otherwise a throw is expected
Show answer
When the function completes it narrows x to T; otherwise a throw is expected — The asserts x is T return type narrows x to T when the function completes normally; if it throws, the flow stops and no narrowing happens. No if condition is needed.
-
Assertion with asserts
function assertString(x: unknown): ____ {
if (typeof x !== "string") throw new Error("not string");
}
Show answer
function assertString(x: unknown): asserts x is string {
if (typeof x !== "string") throw new Error("not string");
}
-
Assertion function parts
- asserts x is T
- assertion function return type
- assertString(v)
- narrows v to string if completes
- throw new Error
- when condition fails
- is ile type guard
- returns true/false
Next lesson: Primitives guard