我正在尝试设置在 Name
接口(interface)中定义的子属性 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
有人有解决这个问题的想法吗?
最佳答案
类属性不会在实例化时自动初始化。您需要使用相应的对象手动初始化它们——在本例中,使用一个包含由其接口(interface)定义的属性的对象:
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
接口(interface) < em>要求对象上存在first
和last
属性。要克服这个错误,可以求助于在接口(interface)上定义可选 属性:
interface Name {
first?: string;
last?: string;
}
关于interface - 在 Typescript 中如何修复无法设置未定义的属性 'first',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36196284/