Type a this parameter
Declare a fake first parameter named this so the compiler checks what a function is called on, and rejects calls with no object. TypeScript 5 and earlier.
A function that reads this.label breaks when it is called without an object. A this parameter documents the requirement and makes the compiler enforce it.
interface Button {
label: string;
}
function describe(this: Button, suffix: string): string {
return `${this.label}${suffix}`;
}
const button = { label: 'Save', describe };
console.log(button.describe('!'));Save!A parameter named this is not a real parameter. It is erased when the code is compiled, and callers do not pass it. Inside the function, this has the type Button, so this.label is a string. A bare call such as describe('x') is an error, TS2684: the this context of type void is not assignable to the method's this of type Button. See [this parameters](https://www.typescriptlang.org/docs/handbook/2/functions.html#declaring-this-in-a-function).
It matters for callbacks, because passing button.describe to setTimeout loses the object at runtime, and the compiler can now see that in some cases. With noImplicitThis, part of strict, a function that uses this with no declared type is also an error. Arrow functions cannot have a this parameter, since they capture this from where they are written.