How to use Immutable JS with typed ES6 classes?

假如想象 提交于 2019-12-04 23:20:28
bertrandg

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/

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!