TS2684
error TS2684: The ‘this
‘ context of type ‘void
‘ is not assignable to method’s ‘this
‘ of type ‘Person
‘.
Broken Code ❌
1 2 3 4 5 6 7 8 9
| type Person = { name: string; };
export function sayHello(this: Person, text: string = 'Hello'): void { console.log(`${text} ${this.name}`); }
sayHello('Welcome');
|
Fixed Code ✔️
When calling a function that defines a this
parameter, then we have to set the this
context with apply
, bind
or call
.
Using apply
:
1 2 3 4 5 6 7 8 9 10 11 12 13
| type Person = { name: string; };
export function sayHello(this: Person, text: string = 'Hello'): void { console.log(`${text} ${this.name}`); }
const benny: Person = { name: 'Benny', };
sayHello.apply(benny, ['Welcome']);
|
Using bind
:
1 2 3 4 5 6 7 8 9 10 11 12 13
| type Person = { name: string; };
export function sayHello(this: Person, text: string = 'Hello'): void { console.log(`${text} ${this.name}`); }
const benny: Person = { name: 'Benny', };
sayHello.bind(benny)('Welcome');
|
Using call
:
1 2 3 4 5 6 7 8 9 10 11 12 13
| type Person = { name: string; };
export function sayHello(this: Person, text: string = 'Hello'): void { console.log(`${text} ${this.name}`); }
const benny: Person = { name: 'Benny', };
sayHello.call(benny, 'Welcome');
|