【问题标题】:Typescript inherited interface and literal string type key errorTypescript继承接口和文字字符串类型键错误
【发布时间】:2017-05-07 03:43:47
【问题描述】:

我有 3 个接口(下面的ABC)都从一个通用接口(下面的Common)扩展而来。我还有一个容器类型,其中包含这 3 个接口的数组(下面的Container)。

我想抓取其中一个数组并从对象中提取一个公共属性,如 getCommon()` 所示:

interface Common {
    common: boolean;
}

interface A extends Common {
    a: A[];
}

interface B extends Common {
    b: B[];
}

interface C extends Common {
    c: C[];
}

type Container = {
    a: A[],
    b: B[],
    c: C[]
};

let item: Container = {
    a: [ { a: [], common: true } ],
    b: [ { b: [], common: true } ],
    c: [ { c: [], common: true } ]
};

type Key = 'a' | 'b' | 'c';

function getCommon (thisKey: Key) {
    return item[thisKey].map(a => a.common); // This line has an error
}

Typescript Playground link

但是,Typescript 2.1 给了我一个编译错误:

Cannot invoke an expression whose type lacks a call signature. 
Type '{ <U>(this: [A, A, A, A, A], callbackfn: (value: A, index: number, array: A[]) => U, 
thisArg?: an...' has no compatible call signatures.

这是 Typescript 中的错误/限制,还是我做错了什么?

【问题讨论】:

    标签: typescript typescript2.1


    【解决方案1】:

    这似乎是一个限制。但是你可以通过给它数组的类型来帮助编译器:(A | B | C)[]

    function getCommon(thisKey: Key) {
        let arr: (A | B | C)[] = item[thisKey];
        return arr.map(a => a.common);
    }
    

    【讨论】:

    • 所以看起来根本问题是TS编译器没有A[] | B[]具有map属性但认为(A | B)[]有?这很糟糕(而且看起来像是一个错误),因为前一种类型实际上比后者更能代表正在发生的事情。
    • 刚刚创建了github.com/Microsoft/TypeScript/issues/13097,因为这似乎是不受欢迎的行为。我们将看看社区/核心团队对此有何评论!
    猜你喜欢
    • 2020-11-04
    • 1970-01-01
    • 2020-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-30
    • 1970-01-01
    相关资源
    最近更新 更多