tsafe icon indicating copy to clipboard operation
tsafe copied to clipboard

Accept callback for `assert` message

Open psychedelicious opened this issue 4 months ago • 1 comments

Sometimes, error messages are expensive to calculate.

It would be nice to be able to provide a callback for msg so that calculation can be deferred until needed.

For example:

/** https://docs.tsafe.dev/assert */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function assert<_T extends true>(condition?: any, msg?: string | () => string): asserts condition {
    if (arguments.length === 0) {
        condition = true;
    }
    if (assertIsRefWrapper.ref !== undefined) {
        assertIsRefWrapper.ref = undefined;
        return;
    }

    if (!condition) {
        throw new AssertionError(typeof msg === 'function' ? msg() : msg);
    }
}

FWIW, tiny-invariant adopts this pattern.

psychedelicious avatar Oct 08 '24 06:10 psychedelicious