Advertisement
Advanced TypeScript, Function Types, Overloads & Optional/Default Parameters

How do 'this' parameter annotations work in a function type, and what problem do they solve?

Short answer

An explicit `this: SomeType` as the FIRST parameter (removed from the actual call signature) tells TypeScript what type 'this' must be when the function is called, letting the compiler catch incorrect method extraction or binding — like passing an object method as a bare…

Save TypeScript mock interview
Advertisement
AModel answer
An explicit `this: SomeType` as the FIRST parameter (removed from the actual call signature) tells TypeScript what type 'this' must be when the function is called, letting the compiler catch incorrect method extraction or binding — like passing an object method as a bare callback where 'this' would be lost.
interface Button {
  label: string;
  onClick(this: Button, event: Event): void;
}
const button: Button = {
  label: 'Save',
  onClick(this: Button, event) {
    console.log(this.label); // 'this' is correctly typed as Button here
  }
};
Real-world example
Catching a bug where a class method is passed as a raw callback (losing its 'this' binding) before it causes a runtime error.
Likely follow-ups
  • How does this relate to needing .bind(this) or an arrow function for event handlers in classes?
Related topics