Search⌘ K

Assertion Functions

Explore how assertion functions in TypeScript help manage exceptions and transform untyped parameters into specific types, enhancing code safety and clarity. Discover how to use built-in and custom assertion functions introduced in TypeScript 3.7 to prevent errors and support type checking during development.

We'll cover the following...

Asserting untyped code

In JavaScript, you must assert the variables’ type since it is not a typed language. While the assertion function is not something you would require using purely TypeScript, it is handy to know in case you have a transpilation error on assertion.

TypeScript 3.3.4
function showLandArea(address, x, y) { // No typê
assert(typeof address === "string");
assert(typeof x === "number");
assert(typeof y === "number");
console.log(`The house ${address.substr(10)} as an area of ${x * y} meters`)
}
showLandArea("1234 Street ABCDE", 10, 5);
// showLandArea("1234 Street ABCDE", "10", "5"); // Assertion will catch the 10 and 5 as string

With TypeScript 3.7 and above, the assert condition (the first parameter of the assert function) must be true ...