ThisParameterType, OmitThisParameter
type ThisParameterType<T> = T extends (this: infer U, ...args: never) => any ? U : unknown;
type OmitThisParameter<T> = unknown extends ThisParameterType<T> ? T : T extends (...args: infer A) => infer R ? (...args: A) => R : T;Read or remove a function this parameter. These aliases do not bind this at runtime.
| Type parameter | Description |
|---|---|
T | A function type, usually typeof fn. If T is not a function with a this parameter, ThisParameterType is unknown and OmitThisParameter returns T. |
Produces: The this parameter type, or a function type with that parameter removed. Neither alias is a runtime function.
Type errors
type error— Calling a function that still has a required this parameter as a free function is a type error under noImplicitThis, which is included in --strict: the this context is void.
- The signatures are from TypeScript 5.9.3 lib.es5.d.ts, formatted for reading. These aliases arrived in TypeScript 3.3.
- Parameters and ReturnType, which ignore this and use the last overload, stay on the Parameters page.
function greet(this: { name: string }, punctuation: string) {
return this.name + punctuation;
}
const fn: OmitThisParameter<typeof greet> = greet.bind({ name: "Ada" });
console.log(fn("!"));
console.log(greet.call({ name: "Ada" }, "?"));
type ThisArg = ThisParameterType<typeof greet>;
const ctx: ThisArg = { name: "Ada" };
console.log(greet.call(ctx, "."));
function plain(n: number) {
return n.toString(16);
}
const unknownThis: ThisParameterType<typeof plain> = "no this parameter, so unknown";
// @ts-expect-error calling greet as a free function has a void this context
false && greet("!");Expected output
Ada!
Ada?
Ada.Related: Parameters and ReturnType, ThisType