我试图设置在Name
接口中定义的子属性first
,但当这样做时,我总是会收到一个错误,例如:
interface Name{
first: string,
last:string,
}
class Person{
private name:Name
public setName(firstName, lastName){
this.name.first = firstName;
this.name.last = lastName;
}
}
var person1 = new Person();
person1.setName('Tracy','Herrera');
当运行它时,我得到错误:Cannot set property 'first' of undefined
有人想办法解决这个问题吗?
类属性在实例化时不会自动初始化。您需要手动用相应的对象初始化它们——在本例中,使用一个包含其接口定义的属性的对象:
class Person {
private name: Name;
public setName(firstName, lastName) {
this.name = {
first: firstName,
last: lastName
};
}
}
另一种方法——例如,如果有多个方法在同一对象上设置属性——是首先将属性初始化为空对象,最好是在构造函数中:
class Person {
private name: Name;
constructor() {
this.name = {};
}
public setName(firstName, lastName) {
this.name.first = firstName;
this.name.last = lastName;
}
public setFirstName(firstName) {
this.name.first = firstName;
}
}
但是,在当前设置中,将{}
分配给this.name
时会产生编译错误,因为Name
接口需要对象上存在first
和last
属性。为了克服这个错误,可以在接口上定义可选属性:
interface Name {
first?: string;
last?: string;
}
您需要将name设置为name类型的对象(即与该界面匹配的形状)。
例如:
this.name = {
first: 'John',
last: 'Doe'
}
如果你想有自由,进行更改,你可以单独使用?
,
interface Name{
first?: string;
last? : string;
}
class Person{
private name:Name
public setName(firstName: string, lastName: string){
this.name = { first: firstName, last: lastName };
}
public setNameSample(firstName: string){
this.name = { first: firstName };
}
public setNameSample1(lastName: string){
this.name = { last: lastName };
}
}
在上面的情况下,如果你不使用?
,你会得到类似于setNameSample
的东西,例如,如果你只需要设置first
:
类型"{first:any;}"不可分配给类型"Name"。所有物中缺少"last"
注意:我认为前面的答案是正确的,这只是一个补充。
您也可以尝试这个
interface Name{
first: string,
last:string,
}
class Person{
private name = {} as Name;
public setName(firstName, lastName){
this.name.first = firstName;
this.name.last = lastName;
}
}
var person1 = new Person();
person1.setName('Tracy','Herrera');