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

In TypeScript, there is a mismatch between the function return type

I am new to TypeScript and trying to follow its recommendations, but I am having trouble understanding this particular issue. https://i.stack.imgur.com/fYQmQ.png After reading the definition of type EffectCallback, which is a function returning void, I t ...

Instead of relying on Vue TypeScript, we are leveraging IntelliJ with TypeScript 5.0.3 to compile our Vue project

My current version of IntelliJ IDEA is 2023.1 (Ultimate Edition) Build #IU-231.8109.175, released on March 28, 2023. I am facing an issue where my project fails to compile using "Vue TypeScript", resulting in some type mismatches being overlooked. In the ...

Seeking clarification on how the Typescript/Javascript and MobX code operates

The code provided below was utilized in order to generate an array consisting of object groups grouped by date. While I grasped the overall purpose of the code, I struggled with understanding its functionality. This particular code snippet is sourced from ...

Utilizing Vue class-style components for creating a recursive component

I'm currently working with a class-style component using the vue-property-decorator plugin. I want to create a recursive component that can use itself within its own structure. Here's a snippet of my code: <template> <ul> <li& ...

Having trouble getting tailwind dark mode to work on next.js?

I have set up a custom boilerplate using next.js(10.0.5) with preact(10.5.12), typescript(4.1.3), and tailwind(2.0.2). I am attempting to incorporate a dark mode feature from Tailwind. I followed the instructions from next-themes in order to add the dark ...

Distribute among an array of specific types

I am trying to achieve this behavior using Typescript: type animals = 'cat' | 'dog' let selectedAnimals: animals[] = ['cat'] selectedAnimals = [ // <- Type 'string[]' is not assignable to type 'animals[]&ap ...

Potential uncertainty in Angular FormControl email validation due to potential null Object

Whenever I run the command ng s --aot, I encounter this message: Object is possibly 'null'. I've been trying various solutions all morning to resolve it, but without success. The issue seems to be related to objects like email.valid, dirty, ...

Revamping elements according to ordered array. Angular version 4.3

Dealing with an array of data that needs to be sorted for displaying in a component seems to be a challenge. Despite having a functional code sample demonstrating the concept, the sorting is not reflected in the Angular app's DOM. The original data i ...

The filter becomes ineffective once I remove the input value

Check out this HTML table containing an input field that filters plans. https://i.stack.imgur.com/UfIw2.png I input the value => 1 The filter successfully works https://i.stack.imgur.com/CsQXh.png Removing the value (1) displays all recordings, totali ...

What's the best approach for revalidating data with mutate in SWR?

Whenever a new album is created in my app, the post request response includes an updated list of all albums. To enhance the user experience, I wanted the newly created content to automatically show up without requiring a page refresh. Although I am famil ...

When converting a PDF to a PNG, the precious data often disappears in the process

I am currently facing a problem with the conversion of PDF to PNG images for my application. I am utilizing the pdfjs-dist library and NodeCanvasFactory functionality, but encountering data loss post-conversion. class NodeCanvasFactory { create(w, h) { ...

In Next.js, I am experiencing an issue where the Tailwind class is being added, but the corresponding

I'm currently in the process of developing a board game where I need to track players and their positions on specific squares. My goal is to display a small colored dot on the square where each player is positioned. Here's a snippet of my templa ...

Utilize the fetch function within a React functional component

I have been experimenting with different methods to fetch data only once before rendering, but I am encountering some challenges: It is not possible to call dispatch in componentDidMount as there is a restriction that it can only be done in Functional c ...

experiencing an excessive amount of rerenders when trying to utilize the

When I call the contacts function from the main return, everything seems fine. However, I encounter an error at this point: const showContacts = React.useCallback( (data: UsersQueryHookResult) => { if (data) { return ( < ...

What is the best way to switch the CSS class of a single element with a click in Angular 2

When I receive data from an API, I am showcasing specific items for female and male age groups on a webpage using the code snippet below: <ng-container *ngFor="let event of day.availableEvents"> {{ event.name }} <br> <n ...

Is it possible for a React selector to retrieve a particular data type?

As a newcomer to React and Typescript, I am currently exploring whether a selector can be configured to return a custom type. Below is a basic selector that returns a user of type Map<string, any>: selectors/user.ts import { createSelector } from ...

I'm curious about the type I can set for the first parameter of setState in TypeScript. Is there a way to pass a dynamically generated state object to setState?

When trying to pass a newState object to setState and add some additional properties under certain conditions, I encountered a type error: I attempted to define the new State as Pick<ItemListState, keyof ItemListState> but received a type error ...

The specified 'contactId' property cannot be found within the data type of 'any[]'

I am attempting to filter an array of objects named 'notes'. However, when I attempt this, I encounter the following error: Property 'contactId' does not exist on type 'any[]'. notes: Array < any > [] = []; currentNot ...

Interactive 3D model movable within designated area | R3F

I am currently facing a challenge in limiting the drag area of my 3D models to the floor within my FinalRoom.glb model. After converting it to tsx using gltfjsx, I obtained the following code: import * as THREE from "three"; import React, { useRe ...

establishing the default value as p-multiselect

Here is the code snippet I am currently working on: export class LkBoardStatus { id : number = 0; descr : string = ''; } In the component.ts file, I have defined the following: //... lkBoardStatusList: LkBoardStatus[] = []; selectedStat ...