我想创建以下类的实例:
class Person {
firstName;
lastName;
birthday;
constructor(props: Person) {
{firstName,lastName,birthday} = props
}
}
var me = new Person({firstName: "donald",
lastName: "trump",
middleName: "john"})
我希望构造函数只选择要分配给“ this”的类的属性,这样me
将是{firstName: "donald", lastName: "trump", birthday: undefined}
我的想法是这样做:
class Person {
firstName;
lastName;
birthday;
constructor(props: Person) {
this.{firstName,lastName,birthday} = props
}
}
var me = new Person({firstName: "donald", lastName: "trump", middleName: "john"})
或类似的东西。
答案 0 :(得分:4)
您可以分为两行:
const {firstName,lastName,birthday} = props;
Object.assign(this, {firstName,lastName,birthday});
现在,如果这只是关于三个属性,请执行以下操作:
this.firstName = props.firstName;
this.lastName = props.lastName;
this.birthday = props.birthday;
它更具可读性,并且速度更快。值得多加一行。
您还可以更改构造函数签名,以便对所需的属性进行解构:
constructor({firstName: string, lastName: string, birthday: Date}) {
this.firstName = firstName;
this.lastName = lastName;
this.birthday = birthday;
}