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

前端 未结 4 499
一个人的身影
一个人的身影 2020-12-20 12:37

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:



        
4条回答
  •  鱼传尺愫
    2020-12-20 13:01

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

提交回复
热议问题