假设我有一个非常简单的带有计算属性的类:
class Person {
firstName: string;
lastName: string;
get fuillName(): string {
return this.firstName + ' ' + this.lastName;
}
}
现在我要创建一个Person
类型的对象:
let p: Person = {
firstName: 'John',
lastName: 'Smith'
};
这给了我一个错误:
输入'{firstName:string; lastName:string; }'不能赋值为'Person'。类型'{firstName:string;中缺少属性'fuillName'; lastName:string; }”。
咦? fullName
是只读属性。所以我跟着this question并实现了一个部分初始化程序:
constructor(init?: Partial<Person>) {
Object.assign(this, init);
}
同样的错误。我知道我可以这样做:
let p = new Person();
p.firstName = 'John';
p.lastName = 'Smith';
console.debug(p.fullName);
但是有没有使用JSON语法初始化类的简写?
答案 0 :(得分:3)
如果您按如下方式定义Person类:
class Person {
firstName?: string;
lastName?: string;
constructor(values: Object = {}) {
Object.assign(this, values);
}
get fullName(): string {
return this.firstName + ' ' + this.lastName;
}
}
您可以按以下方式初始化新用户:
let p = new Person({firstName : 'John', lastName: 'Smith'}); //one line, two assignations
console.log(p.fullName);
更进一步:
class Person {
....// as above
set fullName(fullName: string){
let splitName = fullName.split(" ");
this.firstName = splitName[0] || '';
this.lastName = splitName[1] || '';
}
}
let p = new Person()
p.fullName = "Paul Doe";