I am trying to assert that multiple values are not undefined using TypeScript's asserts feature. While I am able to assert a single value, I am not able to assert multiple values by a single statement. See below.
function assert1(a1: any): asserts a1 {
if (a1 === undefined) throw new Error()
}
function assert2(a1: unknown, a2: unknown) {
assert1(a1)
assert1(a2)
}
const foo = () => Math.random() < 0.5 ? 4999 : undefined
const a = foo()
const b = foo()
assert1(a)
console.log(a + 10) // works as expected, no errors
assert2(a, b)
console.log(a + b) // const b: 4999 | undefined, Object is possibly 'undefined'.(2532)
I spent quite a long time with this but to no avail. Is it possible to make this work? Or do I have to stick with the traditional:
if (!a || !b || !c || !d ...) {
throw ...
}
Thanks for your help and insights.
assertssignature. Yourassert2has no, so that function call asserts nothing.typeof a1 === 'undefined'; unfortunately in JSundefinedcan be redefined... to assign toundefinedyou can usea = void 0assertNotUndefinedand use it for each variable in your case a and b.