Skip to content
jshacks.dev
TypeScript

The ThisParameterType Utility Type in TypeScript, With Examples

ThisParameterType extracts the declared this type of a function. See OmitThisParameter, bind and call, decorators and the errors for a wrong this.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the TypeScript, Vite and npm logos.

ThisParameterType<T> takes a function type and produces the type of its this parameter. A function can declare what this must be when it is called, as a fake first parameter named this that exists only for the compiler. The utility reads that declaration back, so that wrappers, binders and decorators can keep the same requirement. If the function declares no this, the result is unknown. Its companion OmitThisParameter<T> removes the declaration and leaves a function that can be called without a receiver. This post explains the this parameter, the definition, the errors the compiler gives for a wrong receiver, how bind and call use these types, and a wrapper that keeps this intact. It uses TypeScript 6.x, and the references are the ThisParameterType entry and the OmitThisParameter entry in the utility types page.

The this parameter

A function declaration may list this as its first parameter. It is not a real argument, it is erased when the code is compiled, and it states the type that this has inside the body.

this-param.tsTypeScript
function describe(this: { name: string }, punct: string): string {
  return `${this.name}${punct}`;
}

type Self = ThisParameterType<typeof describe>;

const self: Self = { name: "Ada" };

console.log(describe.call(self, "!"));
Text
Ada!

Self is { name: string }, the declared receiver. The call goes through call, which takes the receiver as its first argument and checks it against the declared this type. With the strictBindCallApply option, which is part of strict and on by default from TypeScript 6.0, call, apply and bind are typed from the function they are called on, and that is where these utilities are used in the standard library. The handbook describes the syntax in the section on this parameters.

How it is defined

The utility is a conditional type that infers the this type.

my-this-type.tsTypeScript
type MyThisParameterType<T> = T extends (this: infer U, ...args: never) => any
  ? U
  : unknown;

function plain(x: number): number {
  return x;
}

type N = MyThisParameterType<typeof plain>;

const n: N = "anything";

console.log(n);
Text
anything

For a function with no this declaration, the result is unknown, and any value is assignable to it, which is why the string is accepted. The ...args: never in the pattern makes it match functions with any parameter list. Unlike Parameters, this utility has no constraint on T, so passing a non function type does not error, it returns unknown. The related OmitThisParameter has a matching definition that rebuilds the function type from its parameters and result, without the this.

What the compiler rejects

The reason to declare this is to make a wrong call a compile error. Calling the function without a receiver fails.

no-receiver.tsTypeScript
function describe(this: { name: string }, punct: string): string {
  return `${this.name}${punct}`;
}

describe("!");
Text
no-receiver.ts(5,1): error TS2684: The 'this' context of type 'void' is not assignable to method's 'this' of type '{ name: string; }'.

A plain call has this of type void, and void is not a { name: string }. The check is the whole point of the feature: the body can use this.name with a precise type, and the callers must supply a receiver that has it. The value that ThisParameterType gives you is also checked as an ordinary type.

wrong-self.tsTypeScript
function describe(this: { name: string }, punct: string): string {
  return `${this.name}${punct}`;
}

type Self = ThisParameterType<typeof describe>;

const self: Self = { name: 1 };
Text
wrong-self.ts(7,22): error TS2322: Type 'number' is not assignable to type 'string'.

The error sits on the name property, because Self is { name: string } and the value is a number.

OmitThisParameter and bind

OmitThisParameter<T> is the function type with the this declaration removed. It is the type of the result of bind, because a bound function has its receiver fixed.

bind.tsTypeScript
function describe(this: { name: string }, punct: string): string {
  return `${this.name}${punct}`;
}

const bound: OmitThisParameter<typeof describe> = describe.bind({
  name: "Grace",
});

console.log(bound("?"));
Text
Grace?

bound is (punct: string) => string, and it can be called with no receiver. In the standard library, bind is declared roughly as bind<T>(this: T, thisArg: ThisParameterType<T>): OmitThisParameter<T>: the first argument must match the declared receiver, and the result drops it. If you pass an object without a name, the compiler stops you at the bind call, and that is the benefit of typing this.

One detail makes OmitThisParameter safe on any function. When the function has no this declaration, ThisParameterType is unknown, and the utility returns the type unchanged, so you can apply it without checking.

Methods have no declared this

A method written inside a class or an object literal does not declare this as a parameter. Its this comes from the context, and ThisParameterType has nothing to read.

method.tsTypeScript
class Greeter {
  name = "Ada";

  hi(): string {
    return this.name;
  }
}

type H = ThisParameterType<Greeter["hi"]>;

const h: H = 123;

console.log(typeof h);
Text
number

H is unknown, so the number is accepted. A method's receiver is its class instance, and TypeScript does not record it in the method's type. If you want a method that must be called on the right object, declare this explicitly, as in hi(this: Greeter): string. That also makes a detached call such as const f = greeter.hi; f() an error, and under noImplicitThis it protects against the classic lost this bug.

A wrapper that keeps this

The utility earns its place in higher order functions. A decorator or logger that wraps a function must pass this through, and its type must require the same receiver.

wrapper.tsTypeScript
function describe(this: { name: string }, punct: string): string {
  return `${this.name}${punct}`;
}

function withLog<F extends (this: any, ...args: any[]) => any>(fn: F) {
  return function (
    this: ThisParameterType<F>,
    ...args: Parameters<F>
  ): ReturnType<F> {
    console.log(`calling ${fn.name}`);
    return fn.apply(this, args);
  };
}

const wrapped = withLog(describe);

console.log(wrapped.call({ name: "Ada" }, "."));
Text
calling describe
Ada.

The returned function declares this as the same type that describe declares, takes the same arguments through Parameters, and returns the same type through ReturnType. wrapped.call({ name: "Ada" }, ".") is checked against all three, so a call with a receiver that lacks name fails exactly as it would for the original. Without ThisParameterType, the wrapper would either lose the receiver requirement or hard code a type that goes stale.

ThisParameterType and ThisType

The names are close, and the two do different jobs. ThisParameterType<T> reads the this parameter of a function type, and it is an ordinary conditional type. ThisType<T> is a marker interface that carries no members: inside an object literal whose contextual type includes ThisType<X>, the compiler types this in the methods as X. It is the mechanism used by libraries that accept an object of methods and run them against a state object, and it only has an effect when noImplicitThis is on. The utility types page lists it as an entry of its own, so read the ThisType entry before using it.

Practical patterns

Three patterns cover most real uses. The first is a wrapper, as above: decorators, memoizers, debounce helpers and logging proxies that call the original with the caller's receiver. The second is typing a callback API where the library calls your function with a specific this, as DOM event handlers do: a handler declared function (this: HTMLButtonElement, event: MouseEvent) gets the element typed. The third is extracting the receiver type to build test data: ThisParameterType<typeof handler> gives the shape of the object that a test must supply.

The utility also helps when you migrate older code that depends on this to explicit arguments. Declaring this first makes every caller visible to the compiler, and the migration can proceed function by function.

Arrow functions and strictness

Arrow functions cannot declare a this parameter, because they take this from the surrounding scope. ThisParameterType of an arrow function type is unknown. In a file where noImplicitThis is off, a function body that uses this without a declaration gets any, which hides mistakes. That option is part of strict, which is on by default in TypeScript 6.0, so in a new project this in a standalone function is an error until you declare it, and the this parameter is the way to do it.

When not to use ThisParameterType

Do not reach for it when you can avoid this. A function that takes the object as a normal parameter is easier to type, test and compose than one that depends on a receiver, and most modern code passes the object explicitly. Do not use it to cast around errors: the point of a declared this is the check at the call site. And when you need only the arguments, Parameters is the right tool, since it already leaves this out.

Share

Keep reading

Flat illustration of two options weighed side by side, with the TypeScript, Node.js, npm and JavaScript logos.
TypeScript

Type Annotations vs Type Assertions

A type annotation asks the compiler to check a value, while an assertion tells it to trust you. Learn the difference, the errors and safer alternatives.

6 min read
Flat illustration of an editor window full of code, with the TypeScript, npm and Node.js logos.
TypeScript

Type Inference in TypeScript

TypeScript works out most types for you. Learn how inference treats let and const, arrays, return values and callbacks, and when to write a type yourself.

7 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.