5

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.

6
  • 2
    To assert a value a function must have an asserts signature. Your assert2 has no, so that function call asserts nothing. Commented Jan 17, 2020 at 10:31
  • ..also you should check the type using typeof a1 === 'undefined'; unfortunately in JS undefined can be redefined... to assign to undefined you can use a = void 0 Commented Jan 17, 2020 at 10:35
  • @BrunoGrieder typescript compiler would protect against it. Commented Jan 17, 2020 at 10:36
  • @zerkms ok; good to know Commented Jan 17, 2020 at 10:37
  • Unfortunately I am not aware of any solution to aggregate your assertions. Consider writing one assertNotUndefined and use it for each variable in your case a and b. Commented Jan 17, 2020 at 10:38

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, have not thought of that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.