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; }
John weisz
source share