TypeScript - 多重断言

TypeScript - multiple assertions

我试图断言多个值不是 undefined 使用 TypeScript 的 asserts 功能。虽然我能够断言单个值,但我无法通过单个语句断言多个值。见下文。

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)

我为此花了很长时间,但无济于事。有可能使这项工作吗?还是我必须坚持传统的:

if (!a || !b || !c || !d ...) {
  throw ...
}

感谢您的帮助和见解。

除了断言一个单一的值,您还可以断言条件,这对于范围的其余部分都是真实的(更多信息 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