Understanding Assertion Functions in TypeScript

Avatar of Hemanta Sundaray

Hemanta Sundaray

Published

Assertion functions provide a powerful mechanism for type narrowing and runtime validation.

An assertion function asserts that a certain condition is true. If the condition is false, it throws an error.

Its only purpose is to tell TypeScript's control-flow analysis that if the function completes without throwing an error, then a specific variable must have a narrower, more specific type for the rest of the code block.

Let's start with a function, logModeratorPermissions, that takes a user which could be a Viewer or a Moderator. We also have a helper function, checkIfModerator, that throws an error if the user isn't a moderator.

TypeScript
interface
interface BaseUser
BaseUser
{
BaseUser.username: string
username
: string;
}
interface
interface Viewer
Viewer
extends
interface BaseUser
BaseUser
{
Viewer.level: "viewer"
level
: "viewer";
}
interface
interface Moderator
Moderator
extends
interface BaseUser
BaseUser
{
Moderator.level: "moderator"
level
: "moderator";
Moderator.permissions: string[]
permissions
: string[];
}
function
function checkIfModerator(user: Viewer | Moderator): void
checkIfModerator
(
user: Viewer | Moderator
user
:
interface Viewer
Viewer
|
interface Moderator
Moderator
) {
if (
user: Viewer | Moderator
user
.
level: "viewer" | "moderator"
level
!== "moderator") {
throw new
var Error: ErrorConstructor
new (message?: string) => Error
Error
("Not a moderator");
}
}
const
const logModeratorPermissions: (user: Viewer | Moderator) => void
logModeratorPermissions
= (
user: Viewer | Moderator
user
:
interface Viewer
Viewer
|
interface Moderator
Moderator
) => {
function checkIfModerator(user: Viewer | Moderator): void
checkIfModerator
(
user: Viewer | Moderator
user
);
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
(
user: Viewer | Moderator
user
.permissions);
Error ts(2339) ― Property 'permissions' does not exist on type 'Viewer | Moderator'. Property 'permissions' does not exist on type 'Viewer'.
};

We have a type error because TypeScript doesn't analyze the inside of checkIfModerator to understand its effect. It just sees a function that returns void, so it doesn't narrow the type of user. As a result, even after checkIfModerator runs, TypeScript still thinks user could be Viewer | Moderator.

We fix this by changing checkIfModerator into an assertion function. This explicitly tells TypeScript what to infer about the argument if the function completes successfully (i.e., doesn't throw).

All we need to do is define the return type of the checkIfModerator function(the assertion function) using the asserts keyword. The general syntax looks like this:

TypeScript
asserts [argumentName] is [Type]

Where:

  • asserts: The keyword that begins the assertion signature.

  • [argumentName]: The name of the argument from the function's parameter list that you are narrowing (e.g., user).

  • is: The keyword separating the argument from the type.

  • [Type]: The more specific type you are asserting the argument belongs to (e.g., Moderator).

In our specific case, the return type is: asserts user is Moderator

TypeScript
function
function checkIfModerator(user: Viewer | Moderator): asserts user is Moderator
checkIfModerator
(
user: Viewer | Moderator
user
:
interface Viewer
Viewer
|
interface Moderator
Moderator
): asserts
user: Viewer | Moderator
user
is
interface Moderator
Moderator
{
if (
user: Viewer | Moderator
user
.
level: "viewer" | "moderator"
level
!== "moderator") {
throw new
var Error: ErrorConstructor
new (message?: string) => Error
Error
("Not a moderator");
}
}

The asserts user is Moderator signature provides a direct signal to TypeScript's control-flow analysis. It says, "If you see this function call, and you don't see an error thrown, you must narrow the type of the user variable to Moderator for all code that follows."

Now, the type error is fixed.

TypeScript
interface
interface BaseUser
BaseUser
{
BaseUser.username: string
username
: string;
}
interface
interface Viewer
Viewer
extends
interface BaseUser
BaseUser
{
Viewer.level: "viewer"
level
: "viewer";
}
interface
interface Moderator
Moderator
extends
interface BaseUser
BaseUser
{
Moderator.level: "moderator"
level
: "moderator";
Moderator.permissions: string[]
permissions
: string[];
}
function
function checkIfModerator(user: Viewer | Moderator): asserts user is Moderator
checkIfModerator
(
user: Viewer | Moderator
user
:
interface Viewer
Viewer
|
interface Moderator
Moderator
): asserts
user: Viewer | Moderator
user
is
interface Moderator
Moderator
{
if (
user: Viewer | Moderator
user
.
level: "viewer" | "moderator"
level
!== "moderator") {
throw new
var Error: ErrorConstructor
new (message?: string) => Error
Error
("Not a moderator");
}
}
const
const logModeratorPermissions: (user: Viewer | Moderator) => void
logModeratorPermissions
= (
user: Viewer | Moderator
user
:
interface Viewer
Viewer
|
interface Moderator
Moderator
) => {
function checkIfModerator(user: Viewer | Moderator): asserts user is Moderator
checkIfModerator
(
user: Viewer | Moderator
user
);
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
(
user: Moderator
user
.
Moderator.permissions: string[]
permissions
);
};

TAGS:

TypeScript
Understanding Assertion Functions in TypeScript