在Typescript中如何修复无法设置未定义的属性"first"

Mus*_*kat 15 interface typescript

我正在尝试设置接口中first定义的子属性,Name但是当这样做时,我总是得到一个错误,例如:

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');
Run Code Online (Sandbox Code Playgroud)

运行时我得到错误: Cannot set property 'first' of undefined

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

Joh*_*isz 29

实例化时不会自动初始化类属性.您需要手动使用相应的对象初始化它们 - 在这种情况下,使用包含其接口定义的属性的对象:

class Person {
    private name: Name;

    public setName(firstName, lastName) {
        this.name = {
            first: firstName,
            last: lastName
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

另一种方法 - 例如,如果有多个方法在同一个对象上设置属性 - 首先将属性初始化为空对象,最好是在构造函数中:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

然而,利用当前的设置分配时,这将产生一个编译错误{}this.name,因为Name接口需要的存在下firstlast在物体上属性.要克服此错误,可能需要在接口上定义可选属性:

interface Name {
    first?: string;
    last?: string;
}
Run Code Online (Sandbox Code Playgroud)


Ted*_*erg 5

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

例如:

this.name = {
    first: 'John',
    last: 'Doe'
}
Run Code Online (Sandbox Code Playgroud)


Ang*_*gel 5

如果您想要自由地进行更改,您可以单独执行类似的操作?

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 };
        }
}
Run Code Online (Sandbox Code Playgroud)

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

首先输入 '{: 任何; }' 不可分配给键入“名称”。属性“最后”缺失

注意:我认为前面的答案是可行的,这只是一个补充。