如何使用带有类型ES6类的Immutable JS? [英] How to use Immutable JS with typed ES6 classes?
问题描述
任务
和 TaskGroup
class Task {
constructor(public text:string){}
}
class TaskGroup {
constructor :string =new task group,public task:Task [] = []){}
}
然后在我的Angular 2服务中,我将创建一个不变的TaskGroups列表
@Injectable()
class TaskService {
taskGroups:Immutable.List< TaskGroup> ;;
constructor(){
this.taskGroups = Immutable.List< TaskGroup>([new TaskGroup(Coding tasks)]);
}
}
这样只有taskGroups List是不可变的。无论是内在的都不是。即使我做 Immutable.fromJS(...)
而不是 Immutable.List< Board>(...)
嵌套对象是纯文本的Javascript对象。
不可变JS不允许类继承(使用ES6#562继承Immutable对象)
// can'做这个!
class TaskGroup extends Immutable.Map< string,any> {
constructor(public title:string =new task group,public tasks:Task []){}
}
//它抱怨类没有设置,删除等方法
那么如何创建Immutable类对象?
您可以这样做:
const TodoRecord = Immutable.Record({
id:0,
description:,
completed:false
});
class Todo扩展TodoRecord {
id:number;
描述:string;
completed:boolean;
构造函数(道具){
超(道具);
}
}
let todo:Todo = new Todo({id:1,description:I'm Type Safe!});
不完美但工作。
来自这个伟大的博客文章:
http://blog.jhades.org/angular-2-application-architecture-building-flux-like-apps-using-redux-and-immutable-js-js/
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?
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: http://blog.jhades.org/angular-2-application-architecture-building-flux-like-apps-using-redux-and-immutable-js-js/
这篇关于如何使用带有类型ES6类的Immutable JS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!