Sub topic 12
Typing this
This chapter assumes you know how this behaves in JavaScript: it depends on how a function is called, arrow functions capture it from their surroundings, and bind, call and apply set it explicitly. You should also be comfortable with function types and with calling methods on objects and classes. Here you will learn how TypeScript lets you declare what this must be, how it checks calls against that declaration, and where the checks stop.
The problem: this is decided at the call site
In JavaScript, a function does not own its this. The value is chosen each time the function is called.
function describe() {
return `I am ${this.name}`;
}Called as person.describe(), this is person. Called as describe(), this is undefined in strict mode and modules, or the global object otherwise. The function body looks the same in both cases, so a type checker has nothing to go on unless you tell it what receiver you expect.
The this parameter
TypeScript lets you declare the receiver as a fake first parameter named this. It exists only for the type checker and is erased from the emitted JavaScript.
function describe(this: { name: string }): string {
return `I am ${this.name}`;
}
const person = { name: "Ada", describe };
person.describe(); // ok
// describe(); // error: the 'this' context of type 'void' is not assignableThree things follow from this declaration:
- Inside the body,
thishas the declared type, sothis.nameis checked as astring. - Every call is checked.
person.describe()passes becausepersonhas anameproperty of typestring. A baredescribe()has no receiver, sothisisvoidand the call fails. - The compiled output is
function describe() { ... }. Thethisparameter does not count toward the argument list, sodescribe.lengthis unaffected and callers pass no extra argument.
noImplicitThis
Without a this annotation, what TypeScript does depends on the noImplicitThis compiler option. It is part of strict, so most projects have it on.
- With it off, an unannotated
thisin a standalone function isany, and nothing is checked. - With it on, using
thisin a function whose receiver cannot be determined is an error: "'this' implicitly has type 'any' because it does not have a type annotation."
When the receiver can be determined, no annotation is needed. In an object literal, methods get the literal's own type as this:
const counter = {
count: 0,
increment() {
this.count++; // this is typeof counter
},
};
counter.increment();The same applies to class methods, where this is the class instance type. The annotation is needed mainly for standalone functions that you intend to attach to objects later, and for callbacks that the caller invokes with a specific receiver.
Extracted methods lose their receiver
The most common real-world this bug is passing a method somewhere without its object. By default, TypeScript does not catch it.
class Counter {
count = 0;
increment() {
this.count++;
}
}
const c = new Counter();
const inc = c.increment;
// inc(); // compiles, but throws TypeError at runtime: this is undefinedTypeScript treats inc as a plain () => void. It has no record of where the function came from. Declaring this on the method makes the extraction fail at compile time:
class SafeCounter {
count = 0;
increment(this: SafeCounter) {
this.count++;
}
}
const sc = new SafeCounter();
sc.increment(); // ok
const inc2 = sc.increment;
// inc2(); // error: the 'this' context of type 'void' is not assignableThis gives you a compile-time check instead of a runtime crash. The alternative is to remove the problem, not detect it. An arrow function stored in a property captures this from the constructor:
class BoundCounter {
count = 0;
increment = () => {
this.count++;
};
}
const bc = new BoundCounter();
const inc3 = bc.increment;
inc3(); // ok, this is always the instanceThe trade-off is that each instance gets its own copy of the function, so it is not shared on the prototype. Subclasses also cannot call it through super.increment().
Arrow functions and this
Arrow functions have no this of their own. They use whatever this the enclosing scope has, and you cannot declare a this parameter on one. Writing (this: Foo) => ... is an error.
An arrow function can still be assigned to a type that declares this. The this parameter of the target type is simply ignored, because the arrow never reads its own receiver.
Callbacks that set this
Some APIs call your callback with a particular receiver, such as DOM event handlers or libraries that use call. You can describe that contract by putting this in a function type.
interface Button {
label: string;
}
type ClickHandler = (this: Button, event: string) => void;
function attach(button: Button, handler: ClickHandler): void {
handler.call(button, "click");
}
attach({ label: "OK" }, function (event) {
console.log(`${this.label} received ${event}`);
});The function expression passed to attach has no annotations. Contextual typing supplies both event: string and this: Button. This only works with function expressions or method syntax. If you passed an arrow function here and used this inside it, you would get the outer scope's this, not the Button.
The call handler.call(button, "click") is also checked. With strictBindCallApply (part of strict), call verifies that button matches the handler's this type and that the remaining arguments match its parameters.
bind, call, apply and the this utility types
bind creates a new function with a fixed receiver. With strictBindCallApply on, the result type drops the this parameter. TypeScript provides two utility types that expose this behavior directly:
ThisParameterType<F>extracts the declaredthistype ofF, orunknownif there is none.OmitThisParameter<F>returnsFwithout itsthisparameter.
function describeWith(this: { name: string }, punctuation: string): string {
return `I am ${this.name}${punctuation}`;
}
type Receiver = ThisParameterType<typeof describeWith>; // { name: string }
type Plain = OmitThisParameter<typeof describeWith>; // (punctuation: string) => string
const bound: Plain = describeWith.bind({ name: "Ada" });
bound("!"); // "I am Ada!"If you pass a receiver of the wrong type to bind, call or apply, the compiler reports an error. Without strictBindCallApply, these methods return any and accept anything, which is one reason to keep strict enabled.
ThisType for object-literal builders
Some libraries accept an object of methods and then call them with a different object as this. Vue-style option objects work this way. The marker type ThisType<T> tells the compiler what this should be inside the methods of an object literal. It requires noImplicitThis.
type ObjectDescriptor<D, M> = {
data?: D;
methods?: M & ThisType<D & M>;
};
function makeObject<D, M>(desc: ObjectDescriptor<D, M>): D & M {
const data: object = desc.data ?? {};
const methods: object = desc.methods ?? {};
return { ...data, ...methods } as D & M;
}
const obj = makeObject({
data: { x: 0, y: 0 },
methods: {
moveBy(dx: number, dy: number) {
this.x += dx; // this is { x: number; y: number } & the methods
this.y += dy;
},
},
});
obj.moveBy(5, 5);ThisType<T> is an empty marker interface. It has no members and changes nothing about the types it appears in. The compiler only reads it as an instruction for how to type this in the contextually typed literal.
The polymorphic this type
Do not confuse the this parameter with the this type. Inside a class, this can also be used as a return type that means "the type of the instance the method was called on", including subclasses:
class Builder {
protected parts: string[] = [];
add(part: string): this {
this.parts.push(part);
return this;
}
}
class HtmlBuilder extends Builder {
tag(name: string): this {
return this.add(`<${name}>`);
}
}
new HtmlBuilder().add("text").tag("b"); // still an HtmlBuilderIf add were declared to return Builder, the chained .tag("b") call would fail, since Builder has no tag method. The this return type keeps the subclass type through the chain.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| "'this' implicitly has type 'any'" | Unannotated `this` in a standalone function under `noImplicitThis` | Add a `this:` parameter |
| "The 'this' context of type 'void' is not assignable..." | Calling a function that declares `this` without a receiver | Call it as a method, or use `call` or `bind` |
| Method works when called, crashes when passed as a callback | Receiver lost, and the method does not declare `this` | Declare `this`, bind it, or use an arrow-function property |
| `this` is wrong inside a callback | An arrow function was used where the API supplies `this` | Use a `function` expression |
| `bind` or `call` accepts the wrong receiver silently | `strictBindCallApply` is off | Enable `strict` |
Exercises
Exercise
A class method save() is passed to setTimeout(obj.save, 100) and crashes with "Cannot read properties of undefined". Name two ways to make TypeScript reject this call at compile time or avoid the bug entirely.
Show answer
Declare the receiver on the method, for example save(this: Repo), so that passing obj.save as a bare () => void fails to type-check. Alternatively, avoid the bug by defining save as an arrow-function property, or by passing obj.save.bind(obj) or () => obj.save().
Exercise
What does OmitThisParameter<typeof f> produce when f is function f(this: Date, n: number): string, and why is that type useful?
Show answer
It produces (n: number) => string. It is the type of f.bind(someDate), a function whose receiver is already fixed, so callers no longer need to supply this.