Course contentsShow
← TypeScript
Lesson 281 of 1,7966. FunctionsFree lesson

Declaring this as the First Parameter

How to use this as a special first parameter in function signatures to type the this context.

Declaring this as the First Parameter

What you'll learn: How to tell TypeScript what this should be inside a function, preventing runtime errors from misused context.


The Problem Recap

In JavaScript, this can change depending on how a function is called. You learned in the previous lesson how easy it is to lose the correct this context when passing methods as callbacks or detaching them from their objects.

TypeScript's Solution: Typing this

TypeScript lets you declare this as a special first parameter in your function signature. This isn't a real parameter — callers don't pass it — but it tells TypeScript what type this must be when the function runs.

Syntax

function myFunction(this: SomeType, actualParam: string) {
  // Inside here, TypeScript knows `this` is SomeType
}

The this parameter:

  • Must be the first parameter if present
  • Is not passed by callers — it's a type annotation only
  • Helps TypeScript catch context errors at compile time

Example

interface User {
  name: string;
  greet(this: User): void;
}

const user: User = {
  name: "Alice",
  greet(this: User) {
    console.log(`Hello, ${this.name}`);
  }
};

user.greet(); // ✓ OK

const greetFn = user.greet;
greetFn(); // ✗ Error: The 'this' context is void

TypeScript sees that greetFn loses its User context and warns you before runtime.

Key Takeaway: Declaring this as the first parameter lets TypeScript enforce the correct this context, catching detached method calls and callback mistakes at compile time.