The following code snippet demonstrates the declaration of a variable constObj
within the Test
class. The object constObj
is then assigned to this
in the constructor.
Why must we declare the variable again when it is already being assigned to this
in the constructor?
When using the webstorm
IDE, an error stating
doesn't have the property constObj
is thrown if this.constObj
is not declared. However, the code works without any issues.
Is declaring the variable necessary even though it is being assigned to this
?
const constObj = {
a: function() {
console.log("sivakumar");
}
};
class Test {
constObj: any; // Is this line mandatory? I mean declaring it???
constructor() {
Object.assign(this, {
constObj
});
}
callMethod() {
this.constObj.a();
}
}
new Test().callMethod();
Please explain what would happen if we do not declare the variable.