Table of contents

  1. 1. Assertion Function
  2. 2. Benefits
  3. 3. Disadvantages
    1. 3.1. Incorrect Assertion Function
  4. 4. Assertion Functions in Node.js
  5. 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.

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
type User = {
age: number;
name: string;
}

function assertUser(input: unknown): asserts input is User {
const isObject = input && typeof input === 'object';

if (isObject) {
const hasAge = 'age' in input && typeof input.age === 'number';
const hasName = 'name' in input && typeof input.name === 'string';

if (!hasAge) {
throw new Error('User does not have an age.');
}

if (!hasName) {
throw new Error('User does not have a name.');
}
}

throw new Error('Input is not an object');
}

function printAge(input: unknown) {
// My `input` is unknown here
assertUser(input);
// After passing the assertion function, my `input` is typed
console.log(input.age);
}

// Error: User does not have an age.
printAge({name: 'Benny'});

Benefits

Disadvantages

Incorrect Assertion Function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
type User = {
age: number;
name: string;
}

// This assertion function is insufficient and only checks whether the input existsF
function assertUser(input: unknown): asserts input is User {
if (!input) {
throw new Error('Input is not a User.');
}
}

const user = 1337;
assertUser(user);
// We have convinced TypeScript's compiler that our `number` is of type `User`
console.log(user.name);

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:

1
2
3
4
5
6
7
8
9
import assert from 'node:assert';

function getShortenedText(text?: string): string {
assert.ok(text, 'expected text to be defined');
// Thanks to the "assert" from above, TypeScript knows that "text" is defined:
return text.slice(0, 5);
}

getShortenedText('Benjamin');

Video Tutorial