Specifying the data structure of a complex nested Map in TypeScript

Struggling to create a deeply nested (recursive) Map in Typescript generically. My attempt is to convert the provided Javascript example to Typescript:

const map1 = new Map([
  ['key1', 'value1']
])
const map2 = new Map([
  ['keyA', 'valueB'],
  ['keyB', map1]
])

const map3 = new Map([
  ['keyX', 'valueY'],
  ['keyZ', map2]
])

console.log('map3', map3)

Appreciate any guidance.

Answer №1

Typescript introduces the concept of recursive type references, allowing us to define a map's value as follows:

type StringOrMap = string | Map<string, StringOrMap>

This can be explicitly specified for the Map constructor:

const o2 = new Map<string, StringOrMap>([
  ['b1', 'B'],
  ['b2', o1]
])

const o3 = new Map<string, StringOrMap>([
  ['c1', 'C'],
  ['c2', o2]
])

Explore further in the Playground

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

An unexpected error occurs when attempting to invoke the arrow function of a child class within an abstract parent class in Typescript

Here is a snippet of code that I'm working on. In my child class, I need to use an arrow function called hello(). When I try calling the.greeting() in the parent class constructor, I encounter an error: index.ts:29 Uncaught TypeError: this.hello is ...

Implementing a back button in an RTL layout with Ionic 2

Just starting an Ionic 2 app in Arabic language requires a RTL layout. I decided to go with the side menu template. Adding the following line for configuring the app to RTL perfectly changed everything's direction, except for the back button which st ...

Generating dynamic components using React and TypeScript

Creating a multi-step form using a set of components can be tricky. One approach is to compile all the components into an array and then use the map() method to render them in sequence. const stepComponents = [ <SelectCoach/>, <SelectDate/> ...

What is the most effective method for pausing execution until a variable is assigned a value?

I need a more efficient method to check if a variable has been set in my Angular application so that I don't have to repeatedly check its status. Currently, I have a ProductService that loads all products into a variable when the user first visits the ...

An email value being recognized as NULL

create-employee.html <div class="form-group"> <label for="exampleInputEmail1">Email address</label> <span><input type="text" [required]="!standingQueue" class="form-control" name="exampleInputEmail1" ...

The initial update of the view does not occur when a component property changes in Angular 2 RC6

I am currently facing an issue with a component in my project. This component calls a service to retrieve locally stored JSON data, which is then mapped to an array of objects and displayed in the component view. The problem I am encountering is that the v ...

An error occurs when attempting to redirect with getServerSideProps

When I am logged in, I want to redirect to the /chat page using auth0 for authentication. The error seems to be related to returning an empty string for props, but it does not impact the website as redirection works correctly. The main issue here is the in ...

Passing events from a parent component to dynamically created child components in Angular

UPDATE: I've decided to tackle this issue in a different way by retrieving dynamic child component values in the parent component's save() function, following the accepted answer. I am attempting to create a system where a parent component emits ...

Leveraging a Derived-Class Object Within the Base-Class to Invoke a Base-Class Function with Derived-Class Information

I have a situation where I need to access a method from a derived class in my base generic component that returns data specific to the derived class. The first issue I encountered is that I am unable to define the method as static in the abstract class! ...

Is it feasible to alter the file name while utilizing express-fileUpload library?

Is there a way to modify the file name of an uploaded file on the server side? app.post(URL, (req, res) => { let fileName = req.files.file.name; req.fileUpload; res.statusCode = HTTP_OK; res.send("Good Job") }) The settings I have in uploadF ...

Chaining Assignments in TypeScript

let a: { m?: string }; let b = a = {}; b.m = ''; // Property 'm' does not exist on type '{}'. let a: { m?: string } = {}; let b = a; b.m = ''; // It's OK Link to TypeScript Playground What occurs ...

Guide to integrating a component within another component

Due to the size of this application, I am unable to utilize app.module. Unfortunately, the component I need to implement does not contain a module file. I have attempted to import it and utilize @NgModule, but it has not been successful. An error occur ...

What is the method for storing a JSON object path in a variable for use in a template?

Trying to fetch data from a lengthy path has proven challenging for me. I attempted to store the path in a variable and incorporate it into the template, but encountered some issues. Could someone assist me with this? Here is what I have tried: My store ...

Definition for a function within a specific namespace that returns the specified object

Seeking to define the type of a function within a namespace (L.DomEvent.on(e)) that returns this, I encountered an issue with my JavaScript source code: L.DomEvent = { // @function on(el: HTMLElement, eventMap: Object, context?: Object): this on: ...

What is the best way to set up a property in a service that will be used by multiple components?

Here is an example of how my service is structured: export class UserService { constructor() {} coords: Coordinates; getPosition() { navigator.geolocation.getCurrentPosition(position => { this.coords = [position.coords.latitude, posit ...

Having trouble resolving React within the Formik/dist package due to a custom webpack configuration

Struggling to set up projects from scratch, encountering an issue with webpack not being able to resolve formik's modules while other third-party modules like styled-components work fine. I've tried searching online for a solution but couldn&apos ...

"Error TS2339: The property specified does not exist within type definition", located on the input field

When a user clicks a specific button, I need an input field to be focused with its text value selected entirely to allow users to replace the entire value while typing. This is the markup for the input field: <input type="text" id="descriptionField" c ...

Is there a way to trigger a custom event from a Web Component and then intercept it within a React Functional Component for further processing?

I'm facing an issue with dispatching a custom event called "select-date" from a custom web component date picker to a React functional component. Despite testing, the event doesn't seem to be reaching the intended component as expected. Below is ...

The value of type 'string' cannot be assigned to type '"menu" | "selectedMenu" | undefined' as it is not compatible with the specified types

I'm working on creating a multiple select feature using TypeScript, material-ui, and React. I am encountering an error when trying to set MenuProps.variant = 'menu'. The error message reads: "Type '{ variant: string; PaperProps: { styl ...

I'm having trouble with my code not working for get, set, and post requests. What could be causing this issue and how can I

Here are the TypeScript codes I've written to retrieve product details and delete them. import { Component, OnInit } from '@angular/core'; import {FormGroup,FormBuilder, FormControl, Validators} from "@angular/forms" // other impor ...