如何使用带有类型ES6类的Immutable JS?

时间:2016-01-12 14:44:41

标签: javascript typescript ecmascript-6 angular immutable.js

说我有课程TaskTaskGroup

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

class TaskGroup {
    constructor(public title:string = "new task group", public tasks: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>(...),嵌套对象也只是{&1;}。 Javascript对象。

不可变JS不会假定类继承(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

那么如何创建Immutable类对象?

2 个答案:

答案 0 :(得分:9)

你可以这样做:

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!"});

不完美但有效。

来自这篇精彩的博文: https://blog.angular-university.io/angular-2-application-architecture-building-flux-like-apps-using-redux-and-immutable-js-js/

答案 1 :(得分:3)

您可以使用Immutable创建一个包装器,如this教程中所述:

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);
  }
}

希望这会有所帮助! ;)