The concept of Nested TypeScript Map Value Type

Similar to Nested Typescript Map Type, this case involves nesting on the "value" side.

Typescript Playground

const mapObjectObject: Map<string, string | Map<string, string>> = new Map(Object.entries({
    "a": "b",
    "c": new Map(Object.entries({
        "d": "e",
    }))
})); // ✓

const mapObjectMap: Map<string, string | Map<string, string>> = new Map(Object.entries({
    "a": "b",
    "c": new Map([
        ["d", "e"]
    ])
})); // ✓

const mapMapObject: Map<string, string | Map<string, string>> = new Map([
    ["a", "b"],
    ["c", new Map(Object.entries({
        "d": "e",
    }))
]); // ✗


const mapMapMap: Map<string, string | Map<string, string>> = new Map([
    ["a", "b"],
    ["c", new Map([
        ["d", "e"]
    ])]
]); // ✗

The first two examples work, but the second two do not. Both give an error message:

  Overload 1 of 3, '(iterable: Iterable<readonly [string, string]>): Map<string, string>', gave the following error.
    Argument of type '([string, string] | [string, Map<string, string>])[]' is not assignable to parameter of type 'Iterable<readonly [string, string]>'.
      The types returned by '[Symbol.iterator]().next(...)' are incompatible between these types.
        Type 'IteratorResult<[string, string] | [string, Map<string, string>], any>' is not assignable to type 'IteratorResult<readonly [string, string], any>'.
          Type 'IteratorYieldResult<[string, string] | [string, Map<string, string>]>' is not assignable to type 'IteratorResult<readonly [string, string], any>'.
            Type 'IteratorYieldResult<[string, string] | [string, Map<string, string>]>' is not assignable to type 'IteratorYieldResult<readonly [string, string]>'.
              Type '[string, string] | [string, Map<string, string>]' is not assignable to type 'readonly [string, string]'.
                Type '[string, Map<string, string>]' is not assignable to type 'readonly [string, string]'.
                  Types of property '1' are incompatible.
                    Type 'Map<string, string>' is not assignable to type 'string'.
  Overload 2 of 3, '(entries?: readonly (readonly [string, string])[] | null | undefined): Map<string, string>', gave the following error.
    Type 'Map<string, string>' is not assignable to type 'string'.(2769)

and

No overload matches this call.
  Overload 1 of 3, '(iterable: Iterable<readonly [string, string]>): Map<string, string>', gave the following error.
    Argument of type '([string, string] | [string, Map<string, string>])[]' is not assignable to parameter of type 'Iterable<readonly [string, string]>'.
  Overload 2 of 3, '(entries?: readonly (readonly [string, string])[] | null | undefined): Map<string, string>', gave the following error.
    Type 'Map<string, string>' is not assignable to type 'string'.(2769)

Respectively. Even removing the type declaration does not resolve the issue. Inferred types also return the same error.

Answer №1

Here's a suggestion for TS on types:

const mapMapObject = new Map<string, string | Map<string, string>>([
    ["a", "b"],
    ["c", new Map(Object.entries({
        "d": "e",
    }))
]]);

const mapMapMap = new Map<string, string | Map<string, string>>([
    ["a", "b"],
    ["c", new Map([
        ["d", "e"]
    ])]
]);

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

Is it possible to transform a tuple type into a union?

Is it possible to map a tuple's generic type to a union type? type TupleToUnion<T> = T[keyof T]; // This will include all values in the tuple const value: TupleToUnion<[7, "string"]> = 2; // This assignment should not be permitted since ...

An issue occurred in the modal window following the relocation of project files

I encountered an issue with the modal in my Nativescript project after rearranging a few project files, including the modal. I updated the imports and deleted any compiled JavaScript files to ensure that my project could recompile correctly. Although I&ap ...

Troubleshooting a TypeScript error when trying to access an imported service in Angular 2

I've been working on creating a form that allows users to input required details, which will trigger a server call and save the information. However, no matter what I try, I keep encountering the following error: ORIGINAL EXCEPTION: TypeError: this.po ...

What could be causing TypeScript to forego type inference and default to 'any' in this scenario?

While refactoring parts of our React app in TypeScript, I encountered a challenge that required me to use what I consider to be a less than ideal double type argument. I'm unsure if this is a bug in TypeScript or if there is some type ambiguity causin ...

Develop a wrapper for a function with multiple variations in TypeScript

Encountering an issue with the code below while attempting to create a proxy for a function with multiple overloads: // The target function function original (a: number): boolean; function original (a: string): boolean; function original (a: boolean): bool ...

Issue: Unable to load the file named 'script.ts' while employing chrome.scripting.executeScript

Currently, I am working on developing a chrome extension using Vite with React and Typescript along with CRXJS. This is my initial project in this domain. The issue I am encountering is related to executing a script on the current tab when a button is clic ...

What could be causing the issue with Vite build and npm serve not functioning together?

After shifting from CRA to VITE, I am encountering a problem with serving my app. I successfully build my app using vite build. and can serve it using Vite serve without any issues. However, I want to use npm's serve command. Whenever I run vite bui ...

Accessing nested objects within an array using lodash in typescript

After analyzing the structure of my data, I found it to be in this format: {property: ["a","b"], value : "somevalue" , comparison : "somecomparison"} I am looking for a way to transform it into a nested object like so: { "properties": { "a": { ...

What is the best way to retrieve the response from an Observable/http/async call in Angular?

My service returns an observable that makes an http request to my server and receives data. However, I am consistently getting undefined when trying to use this data. What could be causing this issue? Service: @Injectable() export class EventService { ...

Vuejs fails to properly transmit data

When I change the image in an image field, the new image data appears correctly before sending it to the back-end. However, after sending the data, the values are empty! Code Commented save_changes() { /* eslint-disable */ if (!this.validateForm) ...

Placing options and a clickable element within a collapsible navigation bar

Within my angular project, there are 4 input fields where users need to enter information, along with a button labeled Set All which will populate them. https://i.sstatic.net/1GGh1.png I am wondering how I can organize these input fields and the button i ...

Edit the CSS styles within a webview

When loading the page in NativeScript using web viewing, I encountered a need to hide certain elements on the page. What is the best way to apply CSS styles to HTML elements in this scenario? Are there any alternatives that could be considered? I have been ...

Utilize Page.evaluate() to send multiple arguments

I am facing an issue with the Playwright-TS code below. I need to pass the email id dynamically to the tester method and have it inside page.evaluate, but using email:emailId in the code throws an undefined error. apiData = { name: faker.name.firstNa ...

Looking for help with setting up Nodemailer and installing it via NPM

I am currently developing a mobile application using Ionic with Angular/Typescript, and I'm in need of a front-end solution to dynamically send emails in the background to a specific email address. I tried using emailjs, but it requires JavaScript whi ...

The various types of Angular 2 FormBuilders

As I delved into learning Angular 2, I initially came across ngModel, and later discovered FormGroup/FormBuilder which seemed more suitable for handling complex forms. However, one downside that caught my attention was that by using FormBuilder, we sacrifi ...

VScode has identified potential problems with modules that utilize Angular Ivy, however, this should not cause any major issues

Encountering a problem with using Angular in VSCode, where there seems to be no ngModules due to AngularIvy. The error message indicates an issue with 'CommonModule' not being recognized as an NgModule class: [{ "resource": "[...]src/app/com ...

Struggling to locate the module in React Native with TypeScript configuration

Currently, I am in the middle of transitioning our react-native project from JavaScript to TypeScript. As I attempt to import old modules, I keep encountering the following error: Cannot find module 'numeral' Oddly enough, the 'numeral&apo ...

Using Typescript for-loop to extract information from a JSON array

I'm currently developing a project in Angular 8 that involves utilizing an API with a JSON Array. Here is a snippet of the data: "success":true, "data":{ "summary":{ "total":606, "confirmedCasesIndian":563, "con ...

Mongoose and TypeScript - the _id being returned seems to be in an unfamiliar format

Experiencing unusual results when querying MongoDB (via Mongoose) from TypeScript. Defined the following two interfaces: import { Document, Types } from "mongoose"; export interface IModule extends Document { _id: Types.ObjectId; name: stri ...

Ways to define a static variable within a function using Typescript

There is a common approach to declaring a Static Variable or Function within a Class, demonstrated here: class SomeClass(){ static foo = 1; static fooBar(){ return ++SomeClass.foo; } } However, is it possible to declare a Static Local Variable ...