Specifying the type of this for functions

Following up on specifying the type of this in a class or an interface, functions and methods can now declare the type of this they expect.

By default the type of this inside a function is any.Starting with TypeScript 2.0, you can provide an explicit this parameter.this parameters are fake parameters that come first in the parameter list of a function:

  1. function f(this: void) {
  2. // make sure `this` is unusable in this standalone function
  3. }

this parameters in callbacks

Libraries can also use this parameters to declare how callbacks will be invoked.

Example

  1. interface UIElement {
  2. addClickListener(onclick: (this: void, e: Event) => void): void;
  3. }

this: void means that addClickListener expects onclick to be a function that does not require a this type.

Now if you annotate calling code with this:

  1. class Handler {
  2. info: string;
  3. onClickBad(this: Handler, e: Event) {
  4. // oops, used this here. using this callback would crash at runtime
  5. this.info = e.message;
  6. };
  7. }
  8. let h = new Handler();
  9. uiElement.addClickListener(h.onClickBad); // error!

—noImplicitThis

A new flag is also added in TypeScript 2.0 to flag all uses of this in functions without an explicit type annotation.