【问题标题】:Why is the result of a generic mapped type not equally to an union type?为什么泛型映射类型的结果不等于联合类型?
【发布时间】:2020-09-08 17:30:30
【问题描述】:

给定:

class Foo {
    constructor(readonly id: number, readonly value: string) {}
}

class Bar {
    constructor(readonly id: number, readonly value: string, readonly name: string) {}
}

interface Store {
    foo: Foo;
    bar: Bar;
}

以下函数不会从 Store 的映射类型推断联合类型。

const foo1 = <K extends keyof Store, E extends Store[K]>() => {
    let result: E = undefined!;
    result = new Bar(1, 'some-value', 'some-name') // Type 'Bar' is not assignable to type 'E'
};

但是:

const foo2 = () => {
    let result: Foo | Bar = undefined!;
    result = new Bar(1, 'some-value', 'some-name'); // Ok
};

编译正常。

为什么会发生这种情况,是否有替代方法? :)

【问题讨论】:

  • 考虑foo1&lt;'foo', Foo&gt;();。在这种情况下,您将Bar 放入Foo 类型的变量中。

标签: typescript typescript-generics


【解决方案1】:

简单地说,您从这个函数返回FooBar,但函数本身不能返回E,因为它在编译时不知道K 是什么。

const foo1 = <K extends keyof Store, E extends Store[K]>() => {
    let result: Store[K];
    result = new Bar(1, 'some-value', 'some-name') // works
};

改为返回Store[K],基本上就是Foo | Bar

【讨论】:

    猜你喜欢
    • 2019-08-01
    • 2016-08-11
    • 1970-01-01
    • 2019-04-06
    • 1970-01-01
    • 1970-01-01
    • 2021-12-12
    • 2019-01-12
    相关资源
    最近更新 更多