【问题标题】:How to use Immutable JS with typed ES6 classes?如何将不可变 JS 与类型化的 ES6 类一起使用?
【发布时间】:2016-04-17 05:51:42
【问题描述】:

假设我有课程 TaskTaskGroup

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

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

然后在我的 Angular 2 服务中,我将创建一个不可变的任务组列表

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

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

这种方式只有 taskGroups List 是不可变的。里面的东西都不是。即使我使用Immutable.fromJS(...) 而不是Immutable.List&lt;Board&gt;(...),嵌套对象也是普通的 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

那么如何创建不可变类对象呢?

【问题讨论】:

  • 你可能想看看这个link ;)
  • @Kutyel 包装器是一个不错的概念。也许你应该把它写成文章的答案和链接。
  • 完成,感谢您的建议^_^

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


【解决方案1】:

你可以这样做:

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/

【讨论】:

  • 它不是类型检查构造函数参数。为 id 传递字符串,它就可以工作了!
【解决方案2】:

您可以使用 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);
  }
}

希望这会有所帮助! ;)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-09
    • 1970-01-01
    • 2015-06-08
    • 2017-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多