【问题标题】:User defined type guards don't work with `any` type?用户定义的类型保护不适用于“任何”类型?
【发布时间】:2016-09-06 07:19:56
【问题描述】:

如果我正在编写用户定义的类型保护,如下所示:

interface Cat {
  meow: () => void;
}

function isCat(a: any): a is Cat {
  return a.name === 'kitty';
}

var x: Cat|{};
if(isCat(x)) {
  x.meow(); // OK, x is Cat in this block
}

Typescript 能够在上面的 if 块中找出 x 的类型。

但是,如果我将代码更改为:

var x; // No type here. It's an "any" for now.
if(isCat(x)) {
  x.meow(); // What!? It's type `any`??
}

Typescript 假定 xany,即使在类型保护 if 语句的“安全”范围内。

【问题讨论】:

标签: types typescript


【解决方案1】:

已验证错误。已在此处报告:https://github.com/Microsoft/TypeScript/issues/6015

【讨论】:

  • 感谢您的提醒(以及您为 TS 所做的一切:-P)。
猜你喜欢
  • 2019-01-03
  • 2015-12-19
  • 2021-10-31
  • 1970-01-01
  • 1970-01-01
  • 2018-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多