我正在使用TypeScript构建一些最佳实践.如果我发出一个Web请求,并且我获得了一个带有属性的JSON对象,Name并且Age有一种简单的方法可以将它转换为具有属性Name和Age函数的类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();
Run Code Online (Sandbox Code Playgroud)
在每个字段上复制构造函数可能会变得乏味.我想做一些简单的事情,比如施展它,并希望那些功能现在神奇地存在.他们不是.是否有一些替代方案可以让我免于编写这个笨重的构造函数?
那么使用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"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2047 次 |
| 最近记录: |