在Typescript中如何修复无法设置未定义的属性“first” [英] In Typescript how to fix Cannot set property 'first' of undefined
问题描述
我正在尝试设置 Name
界面中定义的子属性 first
但是什么时候所以我总是得到一个错误,例如:
I'm trying to set a the sub property first
that is defined in the Name
interface but when do so I always get an error for example:
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');
运行时我收到错误:无法设置'first'的属性undefined
任何人都有想法解决这个问题吗?
Any one have an idea to work this out?
推荐答案
在实例化时不会自动初始化类属性。您需要手动使用相应的对象初始化它们 - 在这种情况下,使用包含其接口定义的属性的对象:
Class properties are not automatically initialized on instantiation. You need to initialize them with the corresponding objects manually -- in this case, with an object containing the properties defined by its interface:
class Person {
private name: Name;
public setName(firstName, lastName) {
this.name = {
first: firstName,
last: lastName
};
}
}
另一种方法 - 例如,如果有多个方法在同一个对象上设置属性 - 首先将属性初始化为空对象,最好是在构造函数中:
Another approach -- for example, in case there are multiple methods setting properties on the same object -- is to first initialize the property to an empty object, preferably in the constructor:
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
时出错,因为名称
interface 要求在对象上存在第一个
和 last
属性。要克服此错误,可以使用在接口上定义可选属性:
However, with the current setup this will yield a compile error when assigning {}
to this.name
, because the Name
interface requires the presence of a first
and a last
property on the object. To overcome this error, one might resort to defining optional properties on an interface:
interface Name {
first?: string;
last?: string;
}
这篇关于在Typescript中如何修复无法设置未定义的属性“first”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!