【问题标题】:Calling unions of function types in TypeScript在 TypeScript 中调用函数类型的联合
【发布时间】:2019-02-08 01:07:06
【问题描述】:

在 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());

code at typescriptlang.org

我希望 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?

【问题讨论】:

标签: typescript subtyping structural-typing union-types


【解决方案1】:

只需注释f的返回类型,编译器就会看到你返回的每个函数都与该类型兼容:

function f(): (x: { left: String, right: String }) => String {
    if (true) {
        return (x: {left:String}) => x.left;
    } else {
        return (x: {right:String}) => x.right;
    }
}

【讨论】:

    猜你喜欢
    • 2020-02-25
    • 2019-04-20
    • 2021-04-19
    • 1970-01-01
    • 2021-02-20
    • 2021-09-03
    • 1970-01-01
    • 2017-04-10
    • 1970-01-01
    相关资源
    最近更新 更多