typescript 在打字稿中如何修复无法设置未定义的属性“第一个”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36196284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:01:56  来源:igfitidea点击:

In Typescript how to fix Cannot set property 'first' of undefined

interfacetypescript

提问by Mustafa Dwekat

I'm trying to set a the sub property firstthat is defined in the Nameinterface but when do so I always get an error for example:

我正在尝试设置firstName界面中定义的 sub 属性,但是当这样做时,我总是会收到一个错误,例如:

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');

When running it i get the error: Cannot set property 'first' of undefined

运行它时,我收到错误: Cannot set property 'first' of undefined

Any one have an idea to work this out?

任何人有一个想法来解决这个问题?

回答by John Weisz

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;
    }
}

However, with the current setup this will yield a compile error when assigning {}to this.name, because the Nameinterface requiresthe presence of a firstand a lastproperty on the object. To overcome this error, one might resort to defining optionalproperties on an interface:

但是,对于当前设置,这将在分配{}给时产生编译错误this.name,因为Name接口要求对象上存在 afirst和一个last属性。为了克服这个错误,人们可能会求助于在接口上定义可选属性:

interface Name {
    first?: string;
    last?: string;
}

回答by Ted Nyberg

You need to set nameto an object of type Name(i.e. a shape matching that interface).

您需要将name设置为Name类型的对象(即与该接口匹配的形状)。

For example:

例如:

this.name = {
    first: 'John',
    last: 'Doe'
}

回答by Angel Angel

if you want to have freedom, to make changes, separately you can do something like, using ?,

如果你想拥有自由,做出改变,你可以单独做一些类似的事情,使用?

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 };
        }
}

In the above case if you do not use ?you would get something like in setNameSamplefor example if you need set only first:

在上述情况下,如果您不使用,?您会得到类似的东西setNameSample,例如,如果您只需要设置first

Type '{ first: any; }' is not assignable to type 'Name'. Property 'last' is missing in

输入'{第一个:任何; }' 不可分配给类型 'Name'。缺少属性“last”

Note: I think the previous answer are the way to go, this is just an added.

注意:我认为以前的答案是要走的路,这只是一个补充。