This lesson introduces assertion functions which let us narrow the type of a variable or property for the remainder of the containing scope. We're going to learn how to create an assertion function by using the asserts keyword in the function signature. In particular, we're going to focus on narrowing the unknown type to a more specific type.
'assert' will throw if the condition is not match.
function assert(condition: unknown, name?: string): asserts condition { // Recommended using falsy condition
if (!condition) {
throw TypeError(`${name} is not a number`)
}
}
function assertIsNumber(value: unknown, name?: string): asserts value is number{
if (typeof value !== "number") {
throw TypeError(`${name} is not a number`)
}
}
function add(x: unknown, y: unknown): number {
assert(typeof x === "number", "x");
assert(typeof y === "number", "y");
return x + y;
}
function multiply(x: unknown, y: unknown) {
assertIsNumber(x,"x");
assertIsNumber(y, "y");
return x * y;
}
multiply(10, 5);
|
请发表评论