Tried to pass this with type in a class method and then try to access it in 2 ways:
Create a new JS object and assign a value. (No Error)
{
getName: obj1.getName} in below codeSave it to a new variable(reference) and call it (Gives Error)
const a = obj1.getName;in below code
What is the concept behind these two? When I have defined
this: MyClasssaying it is of typeMyClassthen it should give error for the first one as well.
typescript code
class MyClass {
x:string = "Class value";
getName(this: MyClass) {
return this.x;
}
}
// Creating class object
const obj1 = new MyClass();
console.log(obj1.getName());
// Creating JS object
const obj2 = {x: 'Object Value', getName: obj1.getName}
// Will not give error
console.log(obj2.getName());
// Will give error with below line
const a = obj1.getName;
a();
Error: The 'this' context of type 'void' is not assignable to method's 'this' of type 'MyClass'.(2684)
Ref:
- Typescript Documentation: https://www.typescriptlang.org/docs/handbook/2/classes.html#this-parameters
In the above code
obj2has same signature/definition asMyClassthats why it consider that object as an instance of classMyClassand hence didn't give error.While in second case it has different signature and hence typescript gave error.
If we try to create obj2 with x as a number, then signature gets different and it will give error:
Example:
Error:
The 'this' context of type '{ x: number; getName: (this: MyClass) => string; }' is not assignable to method's 'this' of type 'MyClass'Another example:
Error: