Skip to content

assert

Asserts a condition and narrows the type of the value

103 bytes
since v12.6.0

Usage

The assert function from Radashi is used to assert that a given condition is true. If the condition evaluates to false, the function throws an error. This is a fundamental building block for ensuring that certain conditions are met at runtime.

This utility is particularly useful in TypeScript for its ability to perform type narrowing. It uses the asserts keyword in its signature. When assert(condition) is called and the condition is true, TypeScript understands that the type of any variables involved in the condition can be narrowed down based on that truthiness.

import * as
import _
_
from 'radashi'
function
function processValue(value: string | null | undefined): void
processValue
(
value: string | null | undefined
value
: string | null | undefined) {
import _
_
.
function assert(condition: unknown, error?: string | Error): asserts condition (+1 overload)

Asserts that a condition is true. If the condition is false, an error is thrown. This function uses TypeScript's asserts keyword to narrow the type of the value being asserted.

@seehttps://radashi.js.org/reference/typed/assert

@example

function processValue(value: string | null) {
assert(value, 'Value cannot be null or an empty string')
// value is now narrowed to string
console.log(value.toUpperCase())
}
processValue('hello') // logs "HELLO"
processValue(null) // throws Error: Value cannot be null or an empty string
processValue('') // throws Error: Value cannot be null or an empty string

@example

// Example with false literal, return type is never
const result =
status === 'success'
? 1
: status === 'pending'
? 2
: assert(false, 'Unexpected status')
typeof result
// ^? 1 | 2

@version12.6.0

assert
(
value: string | null | undefined
value
, 'Value cannot be null, undefined, or empty')
// After the assertion, 'value' is narrowed to type 'string'
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 (+1 overload)

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
(
value: string
value
.
String.toUpperCase(): string

Converts all the alphabetic characters in a string to uppercase.

toUpperCase
())
}
function processValue(value: string | null | undefined): void
processValue
('hello') // logs "HELLO"
// _.assert throws on falsy values like:
// - null
// - undefined
// - '' (empty string)
// - 0
// - false
// processValue(null) // throws Error: Value cannot be null, undefined, or empty
// processValue(undefined) // throws Error: Value cannot be null, undefined, or empty
// processValue('') // throws Error: Value cannot be null, undefined, or empty

You can provide an optional message as the second argument to assert. This message will be used as the error message if the assertion fails.

The message can be a string or an instance of the Error class.

  • If a string is provided, a new Error object is created with that string as the message.
  • If an Error instance is provided, that specific error object will be thrown directly.
  • If no message is provided for a failing assertion, a default message "Assertion failed" is used.
import * as
import _
_
from 'radashi'
// Using a custom string message
try {
import _
_
.
function assert(condition: false, error?: string | Error): never (+1 overload)

Asserts that a condition is true. If the condition is false, an error is thrown. This function uses TypeScript's asserts keyword to narrow the type of the value being asserted.

@seehttps://radashi.js.org/reference/typed/assert

@example

function processValue(value: string | null) {
assert(value, 'Value cannot be null or an empty string')
// value is now narrowed to string
console.log(value.toUpperCase())
}
processValue('hello') // logs "HELLO"
processValue(null) // throws Error: Value cannot be null or an empty string
processValue('') // throws Error: Value cannot be null or an empty string

@example

// Example with false literal, return type is never
const result =
status === 'success'
? 1
: status === 'pending'
? 2
: assert(false, 'Unexpected status')
typeof result
// ^? 1 | 2

@version12.6.0

assert
(false, 'This condition failed!')
} catch (
var error: any
error
: any) {
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.error(message?: any, ...optionalParams: any[]): void (+1 overload)

Prints to stderr 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 code = 5;
console.error('error #%d', code);
// Prints: error #5, to stderr
console.error('error', code);
// Prints: error 5, to stderr

If formatting elements (e.g. %d) are not found in the first string then util.inspect() is called on each argument and the resulting string values are concatenated. See util.format() for more information.

@sincev0.1.100

error
(
var error: any
error
.
any
message
) // logs "This condition failed!"
}
// Using a custom Error object
const
const customError: Error
customError
= new
var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+1 overload)
Error
('A specific error occurred.')
try {
import _
_
.
function assert(condition: false, error?: string | Error): never (+1 overload)

Asserts that a condition is true. If the condition is false, an error is thrown. This function uses TypeScript's asserts keyword to narrow the type of the value being asserted.

@seehttps://radashi.js.org/reference/typed/assert

@example

function processValue(value: string | null) {
assert(value, 'Value cannot be null or an empty string')
// value is now narrowed to string
console.log(value.toUpperCase())
}
processValue('hello') // logs "HELLO"
processValue(null) // throws Error: Value cannot be null or an empty string
processValue('') // throws Error: Value cannot be null or an empty string

@example

// Example with false literal, return type is never
const result =
status === 'success'
? 1
: status === 'pending'
? 2
: assert(false, 'Unexpected status')
typeof result
// ^? 1 | 2

@version12.6.0

assert
(false,
const customError: Error
customError
)
} catch (
var error: unknown
error
) {
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.error(message?: any, ...optionalParams: any[]): void (+1 overload)

Prints to stderr 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 code = 5;
console.error('error #%d', code);
// Prints: error #5, to stderr
console.error('error', code);
// Prints: error 5, to stderr

If formatting elements (e.g. %d) are not found in the first string then util.inspect() is called on each argument and the resulting string values are concatenated. See util.format() for more information.

@sincev0.1.100

error
(
var error: unknown
error
===
const customError: Error
customError
) // logs "true"
}

A special case exists when the condition argument is a literal false. In this scenario, the TypeScript signature of assert(false, ...) has a return type of never.

This never return type signals to the TypeScript compiler that the code path following this assertion is unreachable. This can be particularly useful in scenarios like exhaustiveness checks within switch statements or for indicating impossible states in your type logic.

import * as
import _
_
from 'radashi'
type
type Status = "success" | "pending" | "failed"
Status
= 'success' | 'pending' | 'failed'
function
function handleStatus(status: Status): number
handleStatus
(
status: Status
status
:
type Status = "success" | "pending" | "failed"
Status
): number {
return
status: Status
status
=== 'success'
? 1
:
status: "pending" | "failed"
status
=== 'pending'
? 2
:
status: "failed"
status
=== 'failed'
? 3
:
import _
_
.
function assert(condition: false, error?: string | Error): never (+1 overload)

Asserts that a condition is true. If the condition is false, an error is thrown. This function uses TypeScript's asserts keyword to narrow the type of the value being asserted.

@seehttps://radashi.js.org/reference/typed/assert

@example

function processValue(value: string | null) {
assert(value, 'Value cannot be null or an empty string')
// value is now narrowed to string
console.log(value.toUpperCase())
}
processValue('hello') // logs "HELLO"
processValue(null) // throws Error: Value cannot be null or an empty string
processValue('') // throws Error: Value cannot be null or an empty string

@example

// Example with false literal, return type is never
const result =
status === 'success'
? 1
: status === 'pending'
? 2
: assert(false, 'Unexpected status')
typeof result
// ^? 1 | 2

@version12.6.0

assert
(false, `Unknown status: ${
status: never
status
}`)
}
// The return type of handleStatus is number, but the _.assert(false)
// branch has a return type of never, which is compatible.
// This demonstrates using assert(false) as a "throw expression" in
// contexts where the throw keyword isn't allowed, like ternary expressions.