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?
A variable is undefined when it's not assigned any value after being declared. Null refers to a value that is either empty or doesn't exist. null means no value. To make a variable null we must assign null value to it as by default in typescript unassigned values are termed undefined.
To avoid undefined values when using or accessing the optional object properties, the basic idea is to check the property value using an if conditional statement or the optional chaining operator before accessing the object property in TypeScript.
The "Property does not exist on type '{}'" error occurs when we try to access or set a property that is not contained in the object's type. To solve the error, type the object properties explicitly or use a type with variable key names.
In a JavaScript program, the correct way to check if an object property is undefined is to use the typeof operator. If the value is not defined, typeof returns the 'undefined' string.
Class properties are not automatically initialized on instantiation. You need to initialize them with the corresponding objects manually -- in this case, with an 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, in case there are multiple methods setting properties on the same object -- is to first initialize the property to 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 setup this will yield a compile error when assigning {}
to this.name
, because the Name
interface requires the presence of a first
and a last
property on the object. To overcome this error, one might resort to defining optional properties on an interface:
interface Name {
first?: string;
last?: string;
}
You need to set name to an object of type Name (i.e. a shape matching that interface).
For example:
this.name = {
first: 'John',
last: 'Doe'
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With