tsafe
tsafe copied to clipboard
Accept callback for `assert` message
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.