TypeScript - 將普通物件轉換為類別?
我正在使用 TypeScript 建立一些最佳實踐。如果我進行網路請求並得到一個具有屬性 Name 和 Age 的 JSON 物件,有沒有簡單的方法可以將它轉換為我的類別,該類別也具有 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();
TypeScript 遊樂場
讓建構函數複製每個欄位可能會變得很乏味。我希望做一些簡單的事情,比如直接轉型並希望那些函數神奇地出現。但它們並沒有。有沒有某種替代方法可以讓我不用寫這個笨重的建構函數?
答案#1
使用 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"
