Table of contents
- 1. Assertion Function
- 2. Benefits
- 3. Disadvantages
- 3.1. Incorrect Assertion Function
- 4. Assertion Functions in Node.js
- 5. Video Tutorial
An assertion function is the implementation of a runtime check that is able to identify the type of unknown input. When the conditions of the assertion functions are passed, TypeScript’s compiler will then assume that the input is of the type claimed by the signature of the assertion function.
The TypeScript code below examines an
input of type
unknown. If the
assertUser function does not produce an error, TypeScript’s compiler will assume that the
input is of type
User as specified in the signature of the assertion function with
asserts input is User:
- Assertion functions are useful in situations where the type of a value is uncertain, especially when the value originates from external sources such as user input or third-party libraries.
- Assertion functions can check that the input meets certain criteria, and if it doesn’t, they can raise an error, preventing the rest of the code from executing in an undefined state.
- Because the checks of an assertion function are created by the user, it is possible for them to contain errors or omitted conditions.
Incorrect Assertion Function
Assertion Functions in Node.js
If your code is running in a Node.js environment and you have installed
@types/node, you can make use of Node’s built-in module
assert:node to do assertions on your variables: