Skip to content
Tutorials Center
My learning

Topics

TypeScript Reference ยท Utility Types

TypeScript ThisParameterType<T> utility type

Reference for TypeScript ThisParameterType<T>: extract the declared this parameter of a function type, with the unknown fallback and strictBindCallApply notes.

ThisParameterType<T> returns the type of the explicit this parameter of a function type. A function can declare what this must be by listing a fake first parameter named this. That parameter is erased in the output and exists only for checking. This utility reads it back.

If the function does not declare a this parameter, the result is unknown. The type is rarely needed directly, but it is useful in helpers that wrap or bind functions and need to preserve what this has to be.

TypeScript
function describe(this: { name: string }) {
  return this.name;
}

type Owner = ThisParameterType<typeof describe>;
// { name: string }

Try it

TypeScript Reading the this type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TypeScript A typed call helper

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Syntax

TypeScript
type ThisParameterType<T> =
  T extends (this: infer U, ...args: never) => any ? U : unknown;
Name Description
T A function type. Any type is accepted; non-functions give unknown.

Result: the type of this that T declares, or unknown when it declares none.

Edge cases: it is not constrained to function types, so ThisParameterType<string> is unknown and not an error.

Usage notes

  • Explicit only. The type comes from a written this: parameter. Methods in classes and object literals do not get one automatically, so they also give unknown.
  • Erased at runtime. The this parameter is not a real argument. shout.call(self, "!") passes "!" as the first real parameter.
  • noImplicitThis (part of strict) is the option that makes TypeScript check this inside functions that declare it.
  • strictBindCallApply (also in strict) lets call, apply and bind check both this and the arguments.
  • Arrow functions have no this parameter and cannot declare one.
  • Pair with Parameters/ReturnType to build typed wrappers, as in the second example.
  • Removal: OmitThisParameter<T> gives the function type without this.
  • Available since TypeScript 3.3.