Typing this and callbacks

Intermediate · 9 min

Declaring what `this` must be with a fake first parameter, and typing callbacks, including why a void callback type accepts a function that returns a value.

Before thisFunction type expressions and call signaturesParameter and return types

Typed Rocks · 9 min

Typing this and callbacks

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Typed RocksReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A `this` parameter is a fake first parameter, as in `function (this: Counter)`, that tells TypeScript what `this` must be inside the function; it is erased from the output and callers don't pass it as an argument.
  • With a `this` parameter declared, every call is checked, so detaching a method and calling it bare is a compile-time error instead of a runtime crash.
  • Under `strict`, `noImplicitThis` reports any `this` whose type would be `any`, which is usually the cue to add a `this` parameter; arrow functions can't declare one because they don't have their own `this`.
  • A callback is typed with an ordinary function type, inline or named, and a function with fewer parameters than the callback type is still assignable because extra arguments are simply ignored.
  • Callback parameters should only be optional if the caller might really not pass them; marking them optional to make implementations easier forces every implementation to handle `undefined`.
  • A callback type returning `void` accepts a function that returns a value, because the caller has promised to ignore the result; that is why `arr.forEach((x) => out.push(x))` compiles even though `push` returns a number.
  • The relaxed `void` rule only applies when a function is checked against a `void`-returning function type; a function declaration or expression whose own return type is written as `void` still can't return a value.

Two things a signature doesn’t show

A function’s parameter list and return type tell you most of what you need. Two things are left over.

The first is this. In JavaScript, this isn’t fixed by where a function is written but by how it’s called — obj.method() versus a detached method() — as the javascript roadmap covers. A function that reads this.count quietly depends on being called the right way, and nothing in its parameters says so.

The second is callbacks. Typing a parameter that is itself a function uses the function types from the previous lessons, but a few assignability rules there surprise almost everyone the first time.

The this parameter

TypeScript lets you declare what this must be by writing it as a fake first parameter:

interface Counter {
  count: number;
  increment(this: Counter): void;
}

const counter: Counter = {
  count: 0,
  increment() {
    this.count++;
  },
};

counter.increment(); // fine: this is counter

const inc = counter.increment;
inc(); // Error: The 'this' context of type 'void' is not assignable to method's 'this' of type 'Counter'.

this: Counter isn’t a real parameter. It’s erased in the compiled JavaScript, and callers never pass it. What it does is add a check at every call: whatever this will be at runtime has to match. Calling inc() bare gives it no receiver, which TypeScript models as void, so the call is rejected before it can throw Cannot read properties of undefined.

The same works on standalone functions that are meant to be attached somewhere, such as DOM handlers:

function onClick(this: HTMLButtonElement, event: MouseEvent) {
  this.disabled = true;
  console.log(event.clientX);
}

document.querySelector("button")?.addEventListener("click", onClick);

Under strict, the noImplicitThis flag reports any this whose type would otherwise be any. When you see that error in a plain function, a this parameter is usually the fix. Writing this: void does the opposite job: it promises the function never touches this, so it’s safe to pass around detached.

Arrow functions can’t declare a this parameter. They don’t have their own this at all; they use the one from the surrounding scope, and TypeScript types it from there.

Typing callbacks

A callback parameter takes an ordinary function type, written inline or named with an alias:

type OnProgress = (loaded: number, total: number) => void;

function download(url: string, onProgress: OnProgress, onDone?: () => void) {
  onProgress(50, 100);
  onProgress(100, 100);
  onDone?.();
}

download("/file.zip", (loaded) => console.log(`${loaded} bytes`));

Two details here. The arrow function passed in has no annotations because of contextual typing: loaded is a number because OnProgress says so. And it takes only one parameter while OnProgress has two, which is fine. A function that ignores trailing arguments is safe to call with extra ones, so fewer parameters is always assignable. That’s why arr.forEach((x) => ...) works even though forEach passes three arguments.

An optional callback, like onDone?, is called with ?.() so nothing happens when it’s missing.

Be careful about making a callback’s parameters optional. Writing (loaded: number, total?: number) => void doesn’t make life easier for implementers — it tells them total might not be passed, so every implementation has to handle undefined. Only mark a callback parameter optional if your code really sometimes calls it without one. Thanks to the fewer-parameters rule, implementers can already ignore any argument they don’t need.

Why void callbacks accept return values

This one looks like a bug the first time you see it:

const ids: number[] = [];
[1, 2, 3].forEach((n) => ids.push(n)); // push returns a number. No error.

type Notify = () => void;
const notify: Notify = () => 42; // also fine
const result = notify(); // result is void, not number

forEach declares its callback as returning void, and ids.push(n) returns the new length. TypeScript allows it because of what void means in that position: the caller won’t use whatever comes back. Think of a fire-and-forget webhook: the sender never reads the response body, so it makes no difference whether the receiver sends one. Returning a value nobody reads is harmless, and rejecting it would force braces around every short arrow callback.

The protection is still there on the reading side. notify() is typed void, not number, so you can’t accidentally depend on the 42.

This relaxed rule applies only when a function is checked against a void-returning function type. When a function’s own return type is written as void, as in function save(): void { ... }, the compiler checks the body and rejects any return with a value, just as the parameter-and-return-types lesson showed.

One trap follows from it: an async function returns a Promise, so it’s also assignable to () => void. Passing one to forEach compiles, but nothing waits for the promises, and errors inside them go unhandled. typescript-eslint’s no-misused-promises rule catches this, and the linting lesson later in the roadmap covers setting it up.

About the video

Typed Rocks’ video covers the this half of the lesson in depth. It starts with how this behaves inside a plain function, walks through the problem of calling such a function with the wrong receiver, and then shows the this parameter as the fix. It’s a good visual companion to the Counter example above. The callbacks half of this lesson, including the void rule, isn’t in the video, so the text carries it; fsniraj’s callbacks video in the links covers inline and named callback types and optional callbacks with more examples.

Check yourself

  1. 01What does `this: HTMLButtonElement` do in `function onClick(this: HTMLButtonElement, e: MouseEvent)`, and how many arguments do callers pass?

    It declares that `this` inside the function must be an `HTMLButtonElement`, so `this.disabled` type-checks. It is not a real parameter: it is erased when compiling, and callers pass only the one `MouseEvent` argument. TypeScript checks that wherever the function is called, the `this` value matches.

  2. 02An object has `increment(this: Counter) { this.count++; }`. Why is `const inc = counter.increment; inc();` a compile error?

    Calling `inc()` on its own provides no receiver, so `this` would be `undefined` in strict mode JavaScript, and TypeScript models that as a `this` of type `void`. The declared `this: Counter` doesn't accept `void`, so the call is rejected. Without the `this` parameter, the mistake would only show up at runtime.

  3. 03`["a", "b"].forEach((s) => console.log(s))` passes a one-parameter function where `forEach` describes a three-parameter callback. Why is that allowed?

    A function that takes fewer parameters can safely be called with more arguments; JavaScript ignores the extras. So TypeScript treats `(s: string) => void` as assignable to `(value: string, index: number, array: string[]) => void`. The reverse, a callback that requires more parameters than will be passed, is an error.

  4. 04Why does `const ids: number[] = []; [1, 2].forEach((n) => ids.push(n));` compile when `forEach` expects a callback returning `void` and `push` returns a `number`?

    A `void` return in a function type means the caller will not use the result, not that the function must return nothing. Returning a number to a caller that ignores it is harmless, so `(n: number) => number` is assignable to `(n: number) => void`. This rule exists precisely so short arrow callbacks like this one don't need braces.

  5. 05If `void` callbacks may return values, why is `function save(): void { return 1; }` still an error?

    Because here `void` is the function's own declared return type, not a slot it is being assigned into. Writing `: void` on the function itself is a statement about its body, so the compiler checks every `return` and rejects one with a value. The relaxed rule only applies when a value-returning function is assigned to a `void`-returning function type.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark