从POJO

时间:2017-02-24 00:27:19

标签: typescript ecmascript-6

在ES6中,我可以:

class MyClass {
  constructor({a, b, c} = {}) {
    this._a = a;
    this._b = b;
    this._c = c;
  }
}

let data = {"a":3, "b": 44, "c": 55};
let myObject = new MyClass(data);

它只是有效。打字稿的东西我还没有提供字段的值。那么在TypeScript中如何做到这一点呢。优选地,通过最多改变构造函数参数。我不想要一些冗长的东西来实现它。

如果无法做到这一点,那就是打破javascript和ES6的优点并将我带回Java等最终编写一些静态fromData(..)方法的非常坏的消息。哪个会真的让我失望。

那有办法吗?

1 个答案:

答案 0 :(得分:1)

可以在TypeScript中完成;你只需要添加类型信息:

class MyClass {
  _a: number;
  _b: number;
  _c: number;
  constructor({ a, b, c }: { a?: number, b?: number, c?: number } = {}) {
    this._a = a;
    this._b = b;
    this._c = c;
  }
}

let data = { "a": 3, "b": 44, "c": 55 };
let myObject = new MyClass(data);
相关问题