TypeScript Reference ยท Literal and Object Types
TypeScript this parameters
Reference for TypeScript this parameters: declaring the type of this in a function, noImplicitThis, ThisParameterType, OmitThisParameter and callback pitfalls.
A this parameter is a fake first parameter named this that tells the compiler what type this has inside a function. It exists only at compile time: it is erased from the emitted JavaScript and does not take up an argument position.
It matters for standalone functions and callbacks that rely on being called as a method. Under noImplicitThis (part of strict), using this in a function without a known type is an error, and the this parameter is the fix.
function describe(this: { name: string }) { return `I am ${this.name}`; }
Try it
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.
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
function f(this: Type, ...params): R { /* uses this */ } type Fn = (this: Type, ...params) => R; interface Opts { handler(this: Opts, e: string): void }
| Part | Description |
|---|---|
this: Type |
Must be the first parameter; the name this is reserved for it. |
this: void |
States that the function does not use this and may be called detached. |
| Effect on calls | Method calls obj.f() check obj against Type; f.call(x), apply and bind are checked under strictBindCallApply. |
Edge cases: arrow functions cannot declare a this parameter, because they capture this lexically. Class methods already have this typed as the class (or this type for subclasses), so you add a this parameter only to restrict or loosen callers.
Usage notes
noImplicitThis: without it, a barethisin a function expression isany. Turn it on (it is part ofstrict) and annotate where needed.- Polymorphic
thistype: inside a class, the typethisrefers to the actual subclass; it is different from athisparameter. Use the type for fluent APIs (return this). - Object literal methods: with
noImplicitThis,thisin an object literal method is the literal's contextual type. - Library callbacks: DOM event handlers and APIs such as
Array.prototype.map(callback, thisArg)declare theirthistypes; use the parameter to match them. - Utility types:
ThisParameterType<F>extracts it,OmitThisParameter<F>removes it, andThisType<T>(a marker interface) adjuststhisin object literals. - Common mistake: passing
obj.methodas a callback losesthis; bind it or use an arrow wrapper.