问题
With the below code, TypeScript won't recognize the context of thisArg
(which should be a
and should have saySomething()
method. is there another way to give context of thisArg
for TypeScript?
The code:
class A {
saySomething() {
console.log('Hello!');
}
}
class B {
constructor(a: A) {
const boundSaySomething = this.saySomethingMyself.bind(a);
boundSaySomething();
}
saySomethingMyself() {
this.saySomething();
}
}
const test = new B(new A());
the console correctly logs Hello
, but the the type checking is saying
Property 'saySomething' does not exist on type 'B'.(2339)
回答1:
I think this is too confusing for the linter, I rather would play with inheritance. I just suggest you to cast as any , because cast as "A" type won't work :
saySomethingMyself() {
(<any>this).saySomething();
}
回答2:
This answer solved my issue.
Basically, I had to
change the context of this in any function by adding it (and its type) as the first argument to the function.
In my case, I had to change saySomethingMyself
method from saySomethingMyself()
to saySomethingMyself(this: A)
.
Complete updated code:
class A {
saySomething() {
console.log('Hello!');
}
}
class B {
constructor(a: A) {
const boundSaySomething = this.saySomethingMyself.bind(a);
boundSaySomething();
}
saySomethingMyself(this: A) {
(this).saySomething();
}
}
const test = new B(new A());
回答3:
You need to annotate the this
type for your method.
saySomethingMyself(this: A) {
Full solution:
class A {
saySomething() {
console.log('Hello!');
}
}
class B {
constructor(a: A) {
const boundSaySomething = this.saySomethingMyself.bind(a);
boundSaySomething();
}
saySomethingMyself(this: A) {
this.saySomething();
}
}
const test = new B(new A());
Playground
来源:https://stackoverflow.com/questions/62954376/thisarg-context-not-correctly-recognized-in-bound-function-with-typescript