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

this in Callback Typing

Typing addEventListener and other callback APIs that control the this context.

this in Callback Typing

What you'll learn: How to type callbacks like addEventListener where the library controls what this points to inside your function.

The Problem with Callback APIs

Many JavaScript APIs — particularly event listeners — call your callback function with a specific this context. For example, when you use addEventListener, the browser sets this to the element that received the event. TypeScript needs to know about this pattern to provide accurate type checking.

Without proper typing, TypeScript might think this is something it's not, or you might lose important type information about what this refers to inside your callback.

Typing addEventListener

The browser's addEventListener is typed to expect a callback where this refers to the event target. Here's how TypeScript represents this:

const button = document.querySelector('button')!;

button.addEventListener('click', function(event) {
  // TypeScript knows 'this' is HTMLButtonElement
  this.disabled = true;
  console.log(this.textContent);
});

The typing works because addEventListener's callback signature uses a this parameter:

// Simplified version of how it's typed
interface EventListener {
  (this: HTMLButtonElement, event: Event): void;
}

Notice that arrow functions don't work with this-based callbacks if you need to access this — they capture their surrounding context instead.

When You Define Your Own Callback APIs

If you're creating a library that controls this, declare it explicitly:

function callWithContext(callback: (this: { value: number }) => void) {
  callback.call({ value: 42 });
}

callWithContext(function() {
  console.log(this.value); // TypeScript knows this.value exists
});

Key Takeaway: When typing callbacks for APIs that control this (like addEventListener), use a this parameter in the callback signature to tell TypeScript what context the function will receive — regular functions will check against it, while arrow functions will ignore it.