【发布时间】:2017-04-20 22:58:58
【问题描述】:
此代码似乎导致编译错误(使用 TypeScript 1.6.2 检查):
var a: ((input: any) => boolean) | string | RegExp = "foobar";
if (typeof a === 'function') {
a(100); // compile error here
}
编译器说error TS2349: Cannot invoke an expression whose type lacks a call signature.
我在 TS Playground 中输入了这个,发现 a 在 if 子句中有一个 ((input: any) => boolean) | RegExp 类型,这不是我所期望的。当然typeof /abc/返回'object',所以我相信a不应该是if子句中的正则表达式。
我猜这在某种程度上与this issue 和“积极的亚型减少”有关,但我不确定。
显式类型断言 ((<Function>a)(100)) 没有解决我的问题。有没有快速的解决方法?
编辑:更新了问题,因为事实证明这不是特定于 1.6 的问题。
【问题讨论】:
标签: typescript