在 TypeScript 3.0.3 中,以下代码将给出编译时错误:
function f() {
if (true) {
return (x: {left:String}) => x.left;
} else {
return (x: {right:String}) => x.right;
}
}
class C {
left: String = "";
right: String = "";
}
f()(new C());
我希望 f 的类型是function f(): {left:String; right:String} => String
或等价的(例如,Scala 类型检查器报告了这样的类型)。
但是,我收到以下类型错误:
./leftright.ts:17:1 - error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((x: { left: String; }) => String) |
((x: { right: String; }) => String)' has no compatible call signatures.
17 f()(new C());
尽管我们可以引用对象类型联合中的字段,但函数类型的联合似乎不能直接调用。
有什么方法可以修改f()
为可调用的,同时在其中保留if
-statement 吗?