How to convert a nested data structure to an immutable one in a type-safe way when using Immutable?

51 Views Asked by At

Immutable comes with the fromJs function that transforms a regular nested data structure to an immutable one. My problem is that I can't get it to work nicely with Typescript. This is what I have:

type SubData = {
    field1: string;
}

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

const arr: Data[] = [];

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

It says

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

I tried doing

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

but that doesn't help either. How do I fix this?

1

There are 1 best solutions below

5
Teneff On

You can define your list like this

type SubData = Immutable.MapOf<{
    field1: string
}>

type Data = Immutable.MapOf<{
    field0: string;
    subData: List<SubData>;
}>;

const arr: Data[] = [];

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

TS Playground


Edit: By using fromJS your array will be an immutable array (List) with immutable objects and your type doesn't implies that deep immutability.

A function working with List<Data> would be able to do something like:

function workingWithDataList(list: List<Data>) {
    // overwriting a property
    return list.forEach(item => item.field0 = "0");
}