reactjstypescriptsizeimmutable.jsimmutablelist

Immutable JS List size


I don't get how Immutable JS List size will grown.

As in the example on official doc https://facebook.github.io/immutable-js/docs/#/List/push , pushing something in an immutable js List will automatically grown size.

In my code:

const list: List = List();
list.push(object);
console.log(list, list.size);

My output in consolle is:

(1) object
length: 1
___proto___: Array(0)

undefined

That is really different from the aspected output. There is no size, if I use length in my code Typescript tell me that it doesn't exist "length" in List. I use React with Typescript and Immutable.JS

Anybody has an idea of what happens?


Solution

  • Immutability means that operations do not change the original object but instead create a new one.

    In your case the push method will return a new list with all the old elements and the new one you just added.

    Your code should look something like this.

    const list: List = List();
    const newList = list.push(object);
    console.log(list, list.size);
    console.log(newlist, newlist.size);
    

    This should print a size of 0 for the list variable and a size of 1 for the newList variable.