Combining enums in Typescript

Currently, I am working on the task of merging enum maps in my code. Here is what I have so far:

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

However, upon running the code, I encountered an error from the typescript compiler:

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 am struggling to comprehend this error message. Could it be suggesting that one map is being assigned into another instead of properly merging them?

Link to TS playground

Answer №1

Here is the issue that needs addressing: https://i.sstatic.net/aEXMS.png

When working with TypeScript, it seems to infer the type based solely on the first map provided (...twoFromOnw). To avoid this, you can specify in the MapConstructor (right side) so that TypeScript does not automatically determine its type, but instead uses Map:

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

Answer №2

Here is some potentially useful information:

enum Shape {
    circle = 'circle',
    square = 'square',
    triangle = 'triangle',
}

const mapOne: Map<Shape.square, Shape.circle> = new Map([[Shape.square, Shape.circle]]);
const mapTwo: Map<Shape.triangle, Shape.square> = new Map([[Shape.triangle, Shape.square]]);

type Mapping = Map<Shape.square, Shape.circle> & Map<Shape.triangle, Shape.square>

const combineMaps = <K1 extends Shape, V1 extends Shape, K2 extends Shape, V2 extends Shape>(firstMap: Map<K1, V1>, secondMap: Map<K2, V2>): Mapping =>
    new Map<any, any>([ ...firstMap, ...secondMap])

const finalResult = combineMaps(mapOne, mapTwo)

finalResult.set(Shape.square, Shape.circle) // ok
finalResult.set(Shape.triangle, Shape.square) // ok
finalResult.set(Shape.triangle, Shape.circle) // expected error
finalResult.set(Shape.square, Shape.square) // expected error

finalResult.get(Shape.square) //  Shape.circle | undefined
finalResult.get(Shape.triangle) // Shape.square | undefined
finalResult.get(Shape.circle) // expected error

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieving the necessary data from my object to perform a sum calculation in angular

Having trouble retrieving an attribute from an array in my code. In my .ts file, I am fetching data from my backend endpoint like this: export class PostFeedComponent implements OnInit { data: any = {}; constructor(private http: HttpClient) { t ...

Encountering a decorator error in tsyringe while trying to access Experimental support for @injectable

Currently, I am utilizing tsyringe for dependency injection and attempting to execute unit tests. The issue arises when the class is written in TypeScript (ts) and the test file is crafted in JavaScript (js). Upon trying to run my tests using the command T ...

The Vue instance seems to be unable to recognize the shims-vue.d.ts file

I encountered an issue with my Vue file. Here is the code snippet: import Vue from 'vue'; import VueRouter from 'vue-router'; export default Vue.extend({ name: 'MyComponentsName', methods: { doRedirect() { this. ...

Updating directives is required when there is a modification in the input

I created a custom directive that controls the opacity of an element based on an input value: import { Directive, ElementRef, HostListener, Input, OnInit } from '@angular/core'; import { Observable, Subscription } from 'rxjs/Rx'; @Dir ...

Is there a way for me to add a clickable link within a tooltip?

In my title, I want to insert a clickable link like 'Link' or 'a'. The title is ready for any string you input. <MaterialSwitch title={CLICKABLE STRING HERE} /> ...

Is it possible to access ng-content components using @ViewChild?

I have utilized a card template that employs ng-content slots in the following manner: <ng-content select="card-header"></ng-content> <ng-content select="card-body"></ng-content> <ng-content></ng-c ...

What causes the div to appear empty upon creation in the TypeScript file?

Using Typescript tab1: { headings: ['Col 1', 'Col 2', 'Col 3', 'Col 4'], content: [ { col1: 'name of row object', col2: `<div style="width: 550px; height: 40px; b ...

Issue: Transition of FCM to HTTP v1 API from Previous Legacy API

Recently, I have been working on migrating FCM from the legacy API to the HTTP V1 API. Here's a comparison of the "working code before" and after the necessary modifications: Before: const payload = { data: ...

Changing the selection on multiple input fields in Angular

I am working with two select elements in my form. Based on the selected value from the first select, I am filtering data for the second select. Additionally, I have an option to add the same row of form if desired. My issue is that when I select a value fr ...

In the else-branch, a type guard of "not null" results in resolving to "never."

After creating a type guard that checks for strict equality with null: function isNotNull<T> (arg: T): arg is Exclude<T, null> { return arg !== null } Testing it showed that the then-branch successfully removes null from the type. const va ...

Tips on excluding node_modules from typescript in Next.js 13

I am constructing a website in the next 13 versions with TypeScript, using the src folder and app directory. When I execute `npm run dev`, everything functions correctly. However, upon building, I encounter this error... ./node_modules/next-auth/src/core/l ...

Issues with VS Code detecting inline JavaScript variables in an HTML file when referenced in a TypeScript file

In my index.html file, there is an inline script containing various variables... <body> <div id="load-form-here"></div> <script> let formID="abc123" let myBool = true let myArray = ["foo" ...

Endlessly receiving NPM Docx notifications

I am currently working on a project to develop a module for exporting docx files using the npm docx package. However, whenever I try to execute it, I encounter the following error message (despite having imported the necessary components). I have also chec ...

Is there a way to align all child elements to the right side inside a multi-select checkbox dropdown list using Angular?

I am seeking assistance with the following scenarios: I have a multiselect dropdownlist using the ng-multiselect-dropdown control in Angular. The parent and child items are bound using the code below in the HTML file: <ng-multiselect-dropdown name=&qu ...

Matching the Expected Type with Custom SWR Hook's Return Type

Currently, I am working on integrating swr into my project to create a custom block hook using generics. The goal is to have this hook creator accept mapParamsToKey and request methods as parameters and generate an SWR hook function. However, there seems t ...

Tips for merging individual Koa-Routers using Typescript

My approach to organizing routers in my project involved categorizing them based on their purpose. Here's how they are structured: routers/homeRouter.ts import * as Router from 'koa-router'; const router: Router = new Router(); router ...

Using dynamic imports to enhance code by adding the `.at()` function can lead to errors in the process

Below is the content of my .tsconfig configuration file: { "compilerOptions": { "target": "es6", "baseUrl": "./src", "lib": ["dom", "dom.iterable", "esnext&q ...

The error "Cannot access property afs (Angularfirestore) of undefined in the collection.set()" occurred

In the current code snippet below, I am iterating over a collection of data and updating a field if the email matches. The issue arises when trying to set new values where it crashes. The iteration process itself functions correctly, with afs being Angular ...

Encountering issues with connecting to Upstash using next.js 13: receiving error message "Unable to access properties of undefined (reading 'startsWith')."

I'm attempting to establish a connection with upstash's redis using the code snippet below. However, I am encountering an error. Can you identify what the issue might be? 【code】 import { Redis } from "@upstash/redis"; const redis ...

"Receive a warning in the console regarding an issue with React's forwardRef

I have the following code snippet and I am trying to style my Material UI button using the styled-components library: import React from 'react'; import styled from 'styled-components' import { Button as MuiButton } from '@materia ...