Skip to content
jshacks.dev
TypeScript

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.

1 min read
Summarize in AI

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.

describe.tsTypeScript
interface Button {
  label: string;
}

function describe(this: Button, suffix: string): string {
  return `${this.label}${suffix}`;
}

const button = { label: 'Save', describe };
console.log(button.describe('!'));
Text
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.

Share

More snippets

TypeScript

Make every property required with Required

Required of T removes the question mark from every property, which types a config object after its defaults have been filled in. TypeScript 5 and earlier.

1 min read
TypeScript

Declare types for an untyped module

Write a small .d.ts file with declare module so an untyped package gets real function signatures, instead of an implicit any error. TypeScript 5.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.