Search code examples
typescriptassert

TypeScript - multiple assertions


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.


Solution

  • Instead of asserting one single value, you also can assert conditions, which are truthy for the rest of the scope (more infos here):

    function assert(condition: any, msg?: string): asserts condition {
        if (!condition) throw new Error(msg)
    }
    
    const foo = () => Math.random() < 0.5 ? 4999 : undefined
    
    const a = foo()
    const b = foo()
    
    assert(a !== undefined && b !== undefined) // assert a and b are defined
    
    console.log(a + b) // works; a: 4999, b: 4999
    

    Playground sample