Assertion Functions

Assertion functions are similar to user-defined type guards that allow developers to express their assumptions about the type and shape of input data. These functions can be used to check the type and value of variables. TypeScript’s compiler will use this information at design-time to give fast feedback how a type should be used. An assertion function will also be executed at runtime to throw an error if a type check is not passed.

Example:

1
2
3
4
5
function assertString(input: unknown): asserts input is string {
if (typeof input !== 'string') {
throw new Error('Not a string!');
}
}