uft
    Preparing search index...

    Function createAssert

    • Creates an assert function that throws a custom error if the given condition is false.

      Type Parameters

      Parameters

      • ErrorConstructor: T

        The custom Error constructor to use. Must extend the Error class.

      Returns Assert<T>

      An assert function.

      The returned assert function must be explicitly typed to work correctly, otherwise you will see this error:

      Assertions require every name in the call target to be declared with an explicit type annotation. ts(2775)

      See examples below or check out Assert on how to implement this.

      import { type Assert, createAssert, isDefined } from 'uft'

      class MyError extends Error {
      constructor(code: number, message: string) {
      // ...
      }
      }
      // Incorrect, assert is not explicitly typed.
      const assert = createAssert(MyError)
      // Correct, assert is now explicitly typed.
      const assert: Assert<typeof MyError> = createAssert(MyError)

      assert(true, 0, 'oops') // ok
      assert(false, 0, 'oops') // throws new MyError(0, 'oops')

      // Error arguments can be returned from a function
      // which is only called when the condition is false.
      assert(false, () => [0, 'oops'])
      const token: string | undefined
      // might throw new MyError(401, 'missing token')
      assert(token !== undefined, 401, 'missing token')
      token // type: string