问题
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?
回答1:
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/
回答2:
You can make a wrapper with Immutable, as stated in this tutorial:
import { List, Map } from 'immutable';
export class TodoItem {
_data: Map<string, any>;
get text() {
return <string> this._data.get('text');
}
setText(value: string) {
return new TodoItem(this._data.set('text', value));
}
get completed() {
return <boolean> this._data.get('completed');
}
setCompleted(value: boolean) {
return new TodoItem(this._data.set('completed', value));
}
constructor(data: any = undefined) {
data = data || { text: '', completed: false, uuid: uuid.v4() };
this._data = Map<string, any>(data);
}
}
Hope this will help! ;)
来源:https://stackoverflow.com/questions/34746646/how-to-use-immutable-js-with-typed-es6-classes