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: MyClass
saying it is of typeMyClass
then 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