Crafting a recursive Typescript Immutable.js Record through typing

I am currently working on representing a tree-like data structure using immutable js and typescript. At the moment, I am utilizing regular vanilla js objects to depict the nodes within the tree. Below is the type signature.

type NodeType = {
    value: string
    children: List<NodeType>
}

My goal is to convert this into a Record, but I am unsure of the process to achieve this. If I simply do the following:

const defaultValues: NodeType= {
    value: "foo",
    children: List()
}
const NodeRecord = Record(defaultValues)

...it will work fine at the top level, but it will anticipate the children to be of type NodeType rather than RecordOf(NodeType).

If anyone has insight on how to accomplish this, please share. Thank you

Answer №1

If you take a look at the documentation example, it could provide some assistance. The way your NodeType is currently defined only covers default values, not an actual Record.

import type { RecordFactory, RecordOf } from 'immutable';

// Define new Record factory functions using RecordFactory<TProps>.
type NodeTypeProps = { 
  value: string
  children: List<RecordOf<NodeTypeProps>>
};
const defaultValues: NodeTypeProps = { value: "meh" };
const makeNodeType: RecordFactory<NodeTypeProps> = Record(defaultValues);

type NodeType = RecordOf<NodeTypeProps>;
const someNodeType: NodeType = makeNodeType({ value: "some" });

Note: I haven't personally worked with Immutable and Typescript before, but from what I understand, dealing with recursive types like this might require some additional steps to satisfy the TS compiler.

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

Learn how to implement React Redux using React Hooks and correctly use the useDispatch function while ensuring type-checking

I'm curious about the implementation of Redux with Typescript in a React App. I have set up type-checking on Reducer and I'm using useTypedSelector from react-redux. The only issue I have is with loose type-checking inside the case statements of ...

An effective approach to automatically close an Expansion Panel in an Angular Mat when another one is opened

I am attempting to implement functionality where one expansion panel closes when another is opened. By default, the multi attribute is set to "false" and it works perfectly when using multiple expansion panels within an accordion. However, in this case, I ...

Tips for eliminating a single occurrence with Array.prototype.filter()

I am facing an issue in my React app with the deleteNumberFromList method. This function is designed to remove a specific number from the array by utilizing a setter hook: const [valuesList, setValuesList] = useState<number[]>([]); const deleteNumbe ...

Encountered an issue with locating the module 'webpack-cli/bin/config-yargs' while attempting to run webpack-dev

Encountering an error while trying to start the webpack dev server with the command provided below. Despite suggestions that it could be due to outdated webpack versions, I am confident that all components are up to date: [email protected] [email ...

The attribute 'name' cannot be found within the class 'MyComponent'

I'm a beginner in Angular2 and I have no previous knowledge of version 1. Can you help me understand why this error is occurring and guide me on how to fix it? import { Component } from 'angular2/core'; @Component ({ selector: 'my- ...

What could be causing ESLint to run on its own configuration file while working with Typescript?

I have files named .eslintignore and eslintrc.js in close proximity. The contents of my ignore file are as follows: .eslintrc.js dist/* node_modules/* out-tsc/* However, when I access the eslintrc.js file, an error is triggered: Parsing error: ESLint was ...

Are you searching for ways to convert an object into an array?

I have a dynamically built object and I need to extract specific fields (the dynamic ones) from it and convert them into an array. In the following code snippet, my goal is to convert towers[X] into an array of objects. {id: "", description: "Teste", tow ...

Rows in angular ag grid are vanishing when data is filtered

My ag grid includes custom components for each column, but I'm facing an issue where the components disappear when filtering the data. For example: the component inside the row To apply filtering, I use an input with a filtering function: <data-gr ...

Exploring the power of flow.js within an Angular 2 Typescript project

I am trying to incorporate flowjs or ng-flow into my Angular 2 application. After installing the flowjs typings using npm install --save-dev @types/flowjs from However, upon importing it into my component with import { Flow } from 'flowjs';, ...

Error: Element type is invalid: a string was anticipated, but not found

I recently experimented with the example provided in React's documentation at this link and it functioned perfectly. My objective now is to create a button using material-ui. Can you identify what is causing the issue in this code? import * as R ...

Error message while attempting to update devextreme-datagrid: "Received HTTP failure response for an unknown URL: 0 Unknown Error"

Need help with updating the devextreme-datagrid. Can anyone assist? lineController.js router.put("/:id", (req, res) => { if (!ObjectId.isValid(req.params.id)) return res.status(400).send(`No record with given id : ${req.params.id}`); ...

Instructions for opening a URL in a new tab using Angular

Within my Angular 10 application, I am conducting an API call that retrieves an external URL for downloading a pdf file. Is there a method to open this URL in a new browser tab without relying on the window object? I've been using window.open(url) suc ...

Issue with Angular ngFor binding. What could be causing this error to occur?

I have a main component called DOCUMENT. This document receives a URL segment and retrieves an array of associated objects from my database. Then, using @Output() documents = new EventEmitter() and an @Input() in a DOCUMENT VIEW component, I loop through t ...

Create Functions to Encapsulate Type Guards

Is it possible to contain a type guard within a function as shown below? function assertArray(value: any): void { if (!Array.isArray(value)) { throw "Not an array" } } // This doesn't work function example1(value: string | []) { a ...

What is the process for combining two interface declarations into a single interface?

I have a question regarding organizing the properties of an interface: export interface IInvoicesData { invoice: IInvoice; invoiceWithTotals: IInvoice & IInvoiceTotals; } Currently, everything is functioning smoothly and I am able to consolid ...

Receiving feedback from an http.post request and transferring it to the component.ts file in an Angular

Currently, I am facing an issue with passing the response from an http.post call in my TypeScript service component to an Angular 2 component for display on the frontend. Below are the code structures of my service.ts and component.ts: getSearchProfileRes ...

Guide to inheriting functions from a parent component in Angular 2

Hello, I am a beginner in the realm of angular2 and would appreciate any assistance in refining my vocabulary and terminology. Currently, I have a class that consists of two directives structured as follows: In parent.component.ts, the Parent component i ...

Is there a way for Ionic to remember the last page for a few seconds before session expiry?

I have set the token for my application to expire after 30 minutes, and I have configured the 401/403 error handling as follows: // Handling 401 or 403 error async unauthorisedError() { const alert = await this.alertController.create({ header: 'Ses ...

The design of Next.js takes the spotlight away from the actual content on the

Recently, I've been working on implementing the Bottom Navigation feature from material-ui into my Next.js application. Unfortunately, I encountered an issue where the navigation bar was overshadowing the content at the bottom of the page. Despite my ...

Unable to locate the "fcm-node" module in Node.js with TypeScript

When working on a TypeScript project, I usually rely on the fcm-node package to send Firebase push notifications in Node.js. However, this time around, I faced an issue. I know that for TypeScript projects, we also need to install type definitions (@types ...