gpt4 book ai didi

typescript 合并枚举

转载 作者:行者123 更新时间:2023-12-04 03:36:53 30 4
gpt4 key购买 nike

我正在尝试合并枚举映射,代码运行:

enum One {
a = 'a',
}

enum Two {
aa = 'aa',
}

enum Three {
aaa = 'aaa',
}

type unit = One | Two | Three;

const twoFromOne: Map<Two, One> = new Map([[Two.aa, One.a]]);
const threeFromTwo: Map<Three, Two> = new Map([[Three.aaa, Two.aa]]);
const combined: Map<unit, unit> = new Map([
...twoFromOne,
...threeFromTwo,
]);

但是我得到一个 typescript 编译器错误:

const twoFromOne: Map<Two, One>
No overload matches this call.
Overload 1 of 3, '(iterable: Iterable<readonly [Two, One]>): Map<Two, One>', gave the following error.
Argument of type '([Two, One] | [Three, Two])[]' is not assignable to parameter of type 'Iterable<readonly [Two, One]>'.
The types returned by '[Symbol.iterator]().next(...)' are incompatible between these types.
...

我不明白这个错误,它是说一张 map 被分配到另一张 map 而不是合并吗?

Link to TS playground

最佳答案

问题如下: Trys to create a Map that has type Map<Two, One>

TypeScript 以某种方式仅根据您提供的第一个映射 (...twoFromOnw) 推断类型。您可以将 添加到 MapConstructor(右侧),这样 TypeScript 就不会推断那是类型,评估者使用 Map :

const combined: Map<unit, unit> = new Map<unit, unit>([
...threeFromTwo,
...twoFromOne,
]);

关于 typescript 合并枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66718206/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com