将vanilla对象转换为类?

时间:2015-12-10 21:42:52

标签: typescript

我正在使用TypeScript构建一些最佳实践。如果我发出一个Web请求,并且我获得了一个包含属性NameAge的JSON对象,那么有一种简单的方法可以将其转换为具有属性NameAge的类以及函数说PrintPerson

我知道我可以编写一个构造函数,它将对象和字段按字段复制到this中,因此该类具有相同的数据。这是一个微不足道的例子:

interface RawPerson {
    Name: string;
    Age: number;
}

class Person implements RawPerson {
    Name: string;
    Age: number;

  constructor(obj: RawPerson) {
      this.Name = obj.Name;
      this.Age = obj.Age;
  }

  PrintPerson() {
      console.log(this.Name + ' is ' + this.Age);
  }
}

var json = { Name: 'Corey', Age: 26 };
// What works
new Person(json).PrintPerson();
// Something simple I'd like to do (but doesn't work)
// If this worked, I wouldn't need the Person constructor
(<Person>json).PrintPerson();

TypeScript Playground

对每个字段进行构造函数复制可能会变得乏味。我想做一些简单的事情,比如施展它,并希望那些功能现在神奇地存在。他们不是。是否有一些替代方案可以帮助我免于编写这个笨重的构造函数?

1 个答案:

答案 0 :(得分:7)

如何使用Object.assign

interface Object {    
    assign(target: any, ...sources: any[]): any;
}

interface RawPerson {
    Name: string;
    Age: number;
}

class Person implements RawPerson {
    Name: string;
    Age: number;

  constructor(obj: RawPerson) {
      Object.assign(this, obj);
  }

  PrintPerson() {
      console.log(this.Name + ' is ' + this.Age);
  }
}

var json = { Name: 'Corey', Age: 26 };
new Person(json).PrintPerson(); // prints: "Corey is 26"
相关问题