TS2684
The 'this' context of type 'void' is not assignable to method's 'this' of type 'Person'.
Broken Code ❌
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:
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:
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:
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');Note: The TS2684 error may also occur when attempting to call static functions of a class with a private constructor.
