What is the safest method to convert a nested data structure into an immutable one while ensuring type safety when utilizing Immutable library?

When it comes to dealing with immutable data structures, Immutable provides the handy fromJs function. However, I've been facing issues trying to integrate it smoothly with Typescript. Here's what I've got:

type SubData = {
    field1: string;
}

type Data = {
    field0: string;
    subData: SubData[];
};

const arr: Data[] = [];

const list: List<Data> = fromJS(arr);
      ^^^--- compiler error

An error message is displayed stating:

Type 'List<Map<keyof Data, string | List<Map<"field1", string>>>>' is not assignable to type 'List<Data>'

I attempted to resolve this by using:

const list: List<Data> = fromJS<Data[]>(arr);

However, this approach did not provide a solution. Any suggestions on how to rectify this issue?

Answer №1

To define your list in a similar manner, you can use the following syntax:

type SubDetails = Immutable.MapOf<{
    attribute1: string
}>

type DataStructure = Immutable.MapOf<{
    property0: string;
    subDetailsList: List<SubDetails>;
}>;

const dataArray: DataStructure[] = [];

const dataList: List<DataStructure> = fromJS(dataArray)

TS Playground


Note: using fromJS will create an immutable array (List) with immutable objects without deep immutability.

If you have a function that works with List<DataStructure>, it could do something like:

function processDataList(list: List<DataStructure>) {
    // modify a property
    return list.forEach(item => item.property0 = "updated value");
}

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

When working with the "agora-rtc-sdk-ng" package, an error may be thrown by Next.js stating that "window is not defined"

Currently, I am in the process of incorporating the "agora-rtc-sdk-ng" package for live streaming with next.js and typescript. import AgoraRTC from 'agora-rtc-sdk-ng'; However, when I try to import it, an error is thrown as shown below: https:/ ...

Utilizing References in React Components

One of the challenges I am facing involves a Container that needs references to some of its child components: const Container = () => { const blocks: HTMLDivElement[] = []; return ( <div> <Navigation currentBlock={currentBlock} ...

Guide on transforming a tuple of random types into a nested type structure with the help of recursive conditional types

When I responded to the query on whether Typescript Interfaces can express co-occurrence constraints for properties, I shared the following code snippet: type None<T> = {[K in keyof T]?: never} type EitherOrBoth<T1, T2> = T1 & None<T2&g ...

Creating a OneToMany relationship in NestJS entity model

In my current project with NestJS, I am working on defining entity fields. While I have successfully defined a ManyToOne relation, I am facing difficulties in setting up the syntax for a OneToMany relation to match the structure of my other relationships. ...

Ways to modify the access control to permit origin on a specific API URL in React

https://i.stack.imgur.com/tqQwO.png Is there a way to modify the access control allow origin for a URL API? I keep encountering error 500 whenever I try to load the page. After logging in, I included this code snippet: const options = { header ...

Having trouble logging in with Google using React, Redux, and Typescript - encountered an error when attempting to sign in

As a beginner in TS, Redux, and React, I am attempting to incorporate Google Auth into my project. The code seems functional, but upon trying to login, an error appears in the console stating "Login failed." What adjustments should be made to resolve thi ...

Utilizing React and TypeScript: Passing Arguments to MouseEventHandler Type Event Handlers

Can you help me understand how to properly define the event handler handleStatus as type MouseEventHandler, in order to pass an additional argument of type Todo to the function? interface TodoProps { todos: Array<Todos> handleStatus: Mous ...

Guide on setting up and configuring the seeder in MikroORM

Hey there, I recently tried to execute seeders in MikroORM and encountered a problem. I followed all the steps outlined here: . In the MikroORM route folder (alongside mikro-orm.config.ts), I created a seeders directory. I updated mikro-orm.ts with the fo ...

Step-by-Step Tutorial: Displaying Loading Text in Child Components with Angular 4

Within my "event.component" file, I have a nested component (app-grouplist) <div class="group-list"> <app-grouplist [hasStarted]="started" [hasEnded]="ended" Displaying Loading Groups... </app-grouplist> </div> Upon the initial page ...

Implementing a custom type within a generic function

Struggling with a particular problem, I am trying to figure out whether it is possible to pass a custom type or if only native TypeScript types (such as string and number) can be passed into a generic type implementation for an interface: type coordinates ...

Mastering Interpolation in React with TypeScript is essential for creating dynamic and interactive UI components. By leveraging the

Incorporating and distributing CSS objects through ChakraUI presents a simple need. Given that everything is inline, it seems the main issue revolves around "& > div". However, one of the TypeScript (TS) errors highlights an unexpected flagging of ...

VSCode is unable to locate the typeRoots type declarations

I have organized all the type definitions that will be used in my application into a single file. I created a folder named @types and an index.d.ts file that exports every interface/type needed. I updated my tsconfig.json to include the @types folder: { ...

Utilizing formData.append in TypeScript to handle arrays

Hey there! I'm facing an issue while trying to send a form to my Profile endpoint. The problem lies in the 'user:{}' field, as I am unable to properly insert my array data into this specific field. Here is a breakdown of the fields within m ...

Issue with debugging Azure Functions TypeScript using f5 functionality is unresolved

I am encountering issues running my Azure TypeScript function locally in VS code. I am receiving the errors shown in the following image. Can someone please assist me with this? https://i.stack.imgur.com/s3xxG.png ...

Is there a way to turn off the warning overlay in a React application?

I’m currently using react-app-rewired and I am trying to figure out how to turn off the overlay that displays Typescript warnings whenever I compile. It seems like some warnings that are not caught by the VSCode Typescript checker pop up on this overlay ...

What methods can be implemented to ensure ComponentOverride's universality?

These type definitions for markdown-to-jsx don't seem to be generic enough, causing issues like the one mentioned below. For more details, refer to Why is type SFC<AnchorProps> not assignable to type SFC<{}>? /Users/sunknudsen/Sites/sunk ...

What is the best way to trigger a mat-menu to open with just one click, while also automatically closing any other open menus at

I've encountered an issue where if there are multiple menus in the header, opening a menu for the first time works fine. However, if a menu is already open and I try to open another one, it doesn't work as expected. It closes the previously opene ...

Event typeORM on afterUpdate in NestJS

After every update of my data in the log table, I want to insert an entry into another table. To achieve this, I have created an EntitySubscriberInterface. The event is triggering correctly, but the entity array does not include the updated id. async afte ...

The query fails to retrieve results for the specified date and the beginning of the month

I have encountered an issue with my query that is supposed to fetch values between the start and end of the month. Interestingly, when a record is entered on the first day of the month, it doesn't get returned in the query result. Only records entered ...

Converting HTML to an array using Angular

Is there a way to convert HTML into an array of entities? For example: 'hi <em>there</em>' => ['hi', '<em>', 'there', '</em>'] ...