Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Immutable JS with typed ES6 classes?

Say I have classes Task and TaskGroup

class Task{
     constructor(public text:string){}
}

class TaskGroup {
    constructor(public title:string = "new task group", public tasks:Task[] = []){}
}

Then in my Angular 2 service I will create an Immutable List of TaskGroups

@Injectable()
class TaskService {
    taskGroups:Immutable.List<TaskGroup>;

    constructor() {
       this.taskGroups = Immutable.List<TaskGroup>([new TaskGroup("Coding tasks")]);
    }
}

This way only taskGroups List is immutable. Whatever is inside it isn't. Even if I do Immutable.fromJS(...) instead of Immutable.List<Board>(...) the nested objects are plain ol' Javascript objects.

Immutable JS doesn't supposed class inheritance (Inheriting from Immutable object with ES6 #562)

//can't do this!
class TaskGroup extends Immutable.Map<string, any>{
    constructor(public title:string = "new task group", public tasks:Task[]){}
}
//it complained about the class not having methods like set, delete etc

So how to create Immutable class objects?

like image 341
Frozen Crayon Avatar asked Jan 12 '16 14:01

Frozen Crayon


People also ask

Is immutable JS dead?

Update on 12 Aug 2021. Happily, the creator of Immutable JS resumed to maintaining his lib, and commits are regular now.

Are TypeScript records immutable?

js Records in TypeScript. React apps with Redux are built around an immutable state model. Your entire application state is one immutable data structure stored in a single variable.

Is immutable JS fast?

Immutable push is super fast If you see that the elapsed time is 0 msec , it's not a bug: it is indeed very fast. Increase by 10x the number of iterations and see what happens. On my computer push of immutable. js is about 100x faster than push of native javascript .

How does immutable Javascript work?

Immutable data cannot change its structure or the data in it. It's setting a value on a variable that cannot change, making that value a fact, or sort of like a source of truth — the same way a princess kisses a frog hoping it will turn into a handsome prince.


1 Answers

You can do like this:

const TodoRecord = Immutable.Record({
    id: 0,
    description: "",
    completed: false
});

class Todo extends TodoRecord {
    id:number;
    description:string;
    completed: boolean;

    constructor(props) {
        super(props);
    }
}

let todo:Todo = new Todo({id: 1, description: "I'm Type Safe!"});

Not perfect but working.

It comes from this great blog post: https://blog.angular-university.io/angular-2-application-architecture-building-flux-like-apps-using-redux-and-immutable-js-js/

like image 58
bertrandg Avatar answered Oct 04 '22 04:10

bertrandg