In Typescript how to fix Unable to set property “first” from undefined

I try to set the sub first property, which is defined in the Name interface, but 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 I start, I get an error: Cannot set property 'first' of undefined

Anyone have an idea to work on this?

+7
interface typescript
source share
3 answers

Class properties are not automatically initialized when an instance is created. You need to initialize them manually with the corresponding objects - in this case, with the 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, if there are several methods that set properties for the same object - is to first initialize the property with 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 configuration, this will lead to a compilation error when assigning {} to this.name , since the Name interface requires the first and last properties of the object. To overcome this error, you can resort to the definition of additional interface properties:

 interface Name { first?: string; last?: string; } 
+14
source share

You need to set a name for an object of type Name (i.e., a form corresponding to this interface).

For example:

 this.name = { first: 'John', last: 'Doe' } 
+4
source share

if you want to have freedom, 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 case above, if you are not using ? , you will get something like setNameSample , for example, if you need to install only first :

Type '{first: any; } 'is not assigned to the type' Name '. The "last" property is missing in

Note. I think the previous answer is the way it is just added.

+2
source share

All Articles