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

Viewed 38306

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

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

Any one have an idea to work this out?

4 Answers

You can also try this

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