打字稿合并枚举

时间:2021-03-20 04:20:57

标签: typescript

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

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,
]);

但我收到打字稿编译器错误:

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.
...

我不明白这个错误,是不是说一个地图被分配到另一个而不是合并?

Link to TS playground

2 个答案:

答案 0 :(得分:1)

问题如下: 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,
]);

答案 1 :(得分:0)

我只是想也许它会有所帮助:

enum Point {
    a = 'a',
    aa = 'aa',
    aaa = 'aaa',
}

const twoFromOne: Map<Point.aa, Point.a> = new Map([[Point.aa, Point.a]]);
const threeFromTwo: Map<Point.aaa, Point.aa> = new Map([[Point.aaa, Point.aa]]);

type Overloading = Map<Point.aa, Point.a> & Map<Point.aaa, Point.aa>

const createMap = <K1 extends Point, V1 extends Point, K2 extends Point, V2 extends Point>(fst: Map<K1, V1>, scd: Map<K2, V2>): Overloading =>
    new Map<any,any>([ ...fst, ...scd])

const result = createMap(twoFromOne, threeFromTwo)

result.set(Point.aa, Point.a) // ok
result.set(Point.aaa, Point.aa) // ok
result.set(Point.aaa, Point.a) // expected error
result.set(Point.aa, Point.aa) // expected error


result.get(Point.aa) //  Point.a | undefined
result.get(Point.aaa) //  Point.aa | undefined
result.get(Point.a) // expected error