Function assert

  • Asserts that the given condition is true. If the condition is false, an error is thrown.

    Parameters

    • condition: boolean

      The condition to assert.

    • Optional message: string | (() => string | Error)

      An error message or a function that returns either a message or an Error object.

    Returns asserts condition

    Throws

    If the condition is false.

    Example

    Basic usage

    const value: number
    // might throw new Error('value must be greater than 0')
    assert(value > 0, 'value must be greater than 0')
    // might throw new Error('assert condition not satisfied')
    assert(value > 0)

    Type narrowing

    import { isDefined } from 'uft'

    const value: string | undefined
    // might throw new Error('value must be defined')
    assert(isDefined(value), 'value must be defined')
    value // type: string
  • Asserts that the given condition is true. If the condition is false, an error is thrown.

    Type Parameters

    Parameters

    Returns asserts condition

    Throws

    If the condition is false.

    Example

    Basic usage

    class CustomError extends Error {
    constructor(code: number, message: string) {
    super(`${code}: ${message}`)
    }
    }
    const isUser: boolean
    // might throw new CustomError(401, 'Unauthorized')
    assert(isUser, CustomError, 401, 'Unauthorized')

    Type narrowing

    import { isDefined } from 'uft'

    class NotFound extends Error {
    constructor() {
    super('404 Not Found')
    }
    }
    const value: string | undefined
    // might throw new NotFound()
    assert(isDefined(value), NotFound)
    value // type: string

Generated using TypeDoc