TypeScript Typeguards with destructuring parameters

hrirmatl  于 4个月前  发布在  TypeScript
关注(0)|答案(1)|浏览(37)

搜索词

Typeguard
type narrowing
destructuring

建议

如果能使用带有解构参数的typeguard函数,那将使代码更容易阅读。
目前,typeguard不能与解构参数一起使用,这是一个奇怪的特殊情况。

示例

const val: Array<[string, boolean]> = ([] as Array<[string | undefined, boolean]>)
    .filter(([foo, bar]: [string | undefined, boolean]): [foo, bar] is [string, boolean] => foo !== undefined);

const val2: Array<[string, boolean]> = ([] as Array<[string | undefined, boolean]>)
    .filter((val: [string | undefined, boolean]): val is [string, boolean] => val[0] !== undefined);

https://www.typescriptlang.org/play/index.html#src=const%20val%3A%20Array%3C%5Bstring%2C%20boolean%5D%3E%20%3D%20(%5B%5D%20as%20Array%3C%5Bstring%20%7C%20undefined%2C%20boolean%5D%3E)%0D%0A%20%20%20%20.filter((%5Bfoo%2C%20bar%5D%3A%20%5Bstring%20%7C%20undefined%2C%20boolean%5D)%3A%20%5Bfoo%2C%20bar%5D%20is%20%5Bstring%2C%20boolean%5D%20%3D%3E%20foo%20!%3D%3D%20undefined)%3B%0D%0A%0D%0Aconst%20val2%3A%20Array%3C%5Bstring%2C%20boolean%5D%3E%20%3D%20(%5B%5D%20as%20Array%3C%5Bstring%20%7C%20undefined%2C%20boolean%5D%3E)%0D%0A%20%20%20%20.filter((val%3A%20%5Bstring%20%7C%20undefined%2C%20boolean%5D)%3A val is [string, boolean] => val[0]!==undefined) ; 

5tmbdcev

5tmbdcev1#

我担心碰到一个非常老的东西,但我认为我遇到了一个可以解决的问题。
给定这个函数

export function toPolicy (value: any): [string[], null] | [null, Policy] {
  try {
    return [null, policyJSONSchema.validateSync(value) as Policy]
  } catch (err) {
    return [err.errors, null]
  }
}

给定这个调用站点

const [validationErrors, policy] = toPolicy(req.body)
      if (validationErrors !== null) {
        throw new BadRequest(`invalid policy: ${validationErrors.join(', ')}`)
      }
      found.version = policy.version

即使验证错误为空,policy.version策略仍然可能返回null,这是不可能的。

相关问题