TypeScript
asserts is
Learn the asserts x is T syntax.
asserts is
The asserts x is T return type specifies the signature of an assertion function. The function body must throw if the condition fails; on normal completion TypeScript narrows the parameter x to T. No if condition is needed; in the lines after the call x is treated as T.
function assertString(x: unknown): asserts x is string {
if (typeof x !== "string") {
throw new Error("not a string");
}
}
function process(v: unknown): string {
assertString(v);
return v.toUpperCase(); // v: string
}
Narrowing after the call
After calling assertString(v), in subsequent lines v is narrowed to string. No if condition is needed; this makes the code flow more naturally than with a type guard. The throw mechanism explicitly stops execution on error.
function assertNumber(x: unknown): asserts x is number {
if (typeof x !== "number") throw new Error("not a number");
}
function double(v: unknown): number {
assertNumber(v);
return v * 2; // v: number, no if needed
}
Exercise Handle unknown with assertNumber
Define an assertNumber(x: unknown): asserts x is number function (with throw new Error("not a number") when typeof x !== "number"). Write a double(v: unknown): number function: call assertNumber(v), then return v * 2. Print the result via console.log(double(21)).
Show example solution
function assertNumber(x: unknown): asserts x is number {
if (typeof x !== "number") {
throw new Error("not a number");
}
}
function double(v: unknown): number {
assertNumber(v);
return v * 2;
}
console.log(double(21));
Test yourself
-
What should the body of a function with the asserts x is T signature do?
- Return the T value
- Call console.log
- Throw if the condition fails
- Return true/false
Show answer
Throw if the condition fails — A function with the asserts x is T signature must throw if the condition fails; on normal completion TypeScript narrows x to T. No return is needed.
-
asserts keyword
function assertString(x: unknown): ____ x is string {
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");
}
-
asserts is parts
- asserts x is T
- assertion signature
- throw yapma
- in body when condition fails
- çağrı sonrası daraltma
- no if needed
- assertString(v)
- next line: v is string
Next lesson: asserts defined