【问题标题】:Typescript merge enums打字稿合并枚举
【发布时间】:2021-03-20 22:51:21
【问题描述】:

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

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

【问题讨论】:

标签: typescript


【解决方案1】:

问题如下:

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

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

【讨论】:

    【解决方案2】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 2020-04-30
      • 1970-01-01
      • 2017-05-09
      • 2020-10-27
      • 1970-01-01
      • 2020-01-29
      • 2019-03-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多