Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript merge enums

Tags:

typescript

I'm trying to merge enum maps, the code runs:

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

but I get a typescript compiler error:

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

I don't understand the error, is it saying one map is being assigned into another instead of a merge?

Link to TS playground

like image 541
WBC Avatar asked Jan 25 '26 16:01

WBC


1 Answers

The problem is the following: Trys to create a Map that has type Map<Two, One>

TypeScript somehow infers the type based on only the first map that you provide ( ...twoFromOnw). You can add <unit, unit> to the MapConstructor (right side), so TypeScript will not infers thats type, rater use Map<unit, unit>:

const combined: Map<unit, unit> = new Map<unit, unit>([
    ...threeFromTwo,
    ...twoFromOne,
]);
like image 65
Zoltán Dobrovolni Avatar answered Jan 27 '26 08:01

Zoltán Dobrovolni



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!