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?
Update on 12 Aug 2021. Happily, the creator of Immutable JS resumed to maintaining his lib, and commits are regular now.
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.
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 .
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With