Assert.type()

Syntax

function type(value: unknown, type: TypeofResult, name?: string): void

Asserts that a value has a certain type.

Parameters
value

The value to check.

type

A valid typeof return type. This function checks whether typeof value === type.

name Optional

A variable, property, or parameter name which, if specified, will print the name as part of the assertion error to make it more clear where the error originated.

Example

import { Assert } from 'potence';

function ensureValueIsNumber(arg: unknown) {
    Assert.type(arg, 'number', 'arg');
}

ensureValueIsNumber(5);        // OK
ensureValueIsNumber('hello');  // AssertionError: 'Assertion failed: expected arg to be of type number but was "hello"'

Remarks

This function is a TypeScript assertion function meaning it behaves exactly the same as if (typeof value === type) { ... }, narrowing the type to exclude null and undefined if possible.