我正在创建一个访问twitch API的角度应用程序。数据以不同的支出返回,其中一些我想反序列化并存储在几个类中。
我想知道的是,与从反序列化的 json数据手动分配属性相比,使用Object.assign
实例化类的风险是什么?
我现在有什么:
export class UserDetails implements Serializable<UserDetails>{
public _id: number;
public bio: string;
public created_at: string;
public display_name: string;
public email: string;
public email_verified: boolean;
public logo: string;
public name: string;
public notifications: Object;
public partnered: boolean;
public twitter_connected: boolean;
public type: string;
public updated_at: string;
constructor() {}
deserialize(input: any) {
this._id = input._id;
this.bio = input.bio;
this.created_at = input.created_at;
this.display_name = input.display_name;
this.email = input.email;
this.email_verified = input.email_verified;
this.logo = input.logo;
this.name = input.name;
this.notifications = input.notifications;
this.partnered = input.partnered;
this.twitter_connected = input.twitter_connected;
this.type = input.type;
this.updated_at = input.updated_at;
return this;
}
}
使用Object.assign
可以获得什么。
export class UserDetails implements Serializable<UserDetails>{
constructor() {}
deserialize(input: any) {
Object.assign(this, input);
return this;
}
}
我即将创建一个新类,它将拥有近70个属性....这是最好的方法吗?
事后补充 ......或者我应该实际混合2,所以我仍然得到intellisense?
export class UserDetails implements Serializable<UserDetails>{
public _id: number;
public bio: string;
public created_at: string;
public display_name: string;
public email: string;
public email_verified: boolean;
public logo: string;
public name: string;
public notifications: Object;
public partnered: boolean;
public twitter_connected: boolean;
public type: string;
public updated_at: string;
constructor() {}
deserialize(input: any) {
Object.assign(this, input);
return this;
}
}
答案 0 :(得分:0)
在我看来,拥有公共级别的领域是有益的,原因有两个:
Object.assign
可以向对象添加非声明字段。示例(fiddle link):
class Person {
firstName;
lastName;
deserialize(input: any) {
Object.assign(this, input);
return this;
}
}
let p = new Person();
p.deserialize({firstName:"John", lastName:"Doe", sex:"M"});
console.log(p); //<-- logs: Person { firstName: 'John', lastName: 'Doe', sex: 'M' }
console.log(p.sex); //<-- this logs 'M' to console in JSFiddle.
请注意,propoerty sex
已添加到p
,但是,直接访问该属性就像在第二个console.log
中完成一样,应该引发以下编译错误(尽管它有效)在JSFiddle,不完全确定原因):
TSError:⨯无法编译TypeScript
nodesrc \ test.ts(13,15):属性&#39;性别&#39;类型&#39; Person&#39;中不存在。 (2339)...
因此,如果您希望使用这种类型安全性,那么声明字段可能会有所帮助。
希望这有帮助。