13

Recently when I use Rxjs 5, I downloaded Rxjs by using npm install Rxjs@5.0.1, from downloaded code under node_modules, I found Observable.d.ts in Rxjs folder, I saw it declare its constructor like below:

 *
 * @constructor
 * @param {Function} subscribe the function that is  called when the Observable is
 * initially subscribed to. This function is given a Subscriber, to which new values
 * can be `next`ed, or an `error` method can be called to raise an error, or
 * `complete` can be called to notify of a successful completion.
 */
constructor(subscribe?: <R>(this: Observable<T>, subscriber: Subscriber<R>) => TeardownLogic);

My question is: what is the usage of this keyword in function type declaration of subscribe?: (this: Observable, ...), Does TypeScript has some documentation for this keyword usage like here? Thank you.

IcyBrk
  • 1,090
  • 12
  • 21

1 Answers1

18

You can (since version 2.0 of typescript) specify what is the this you're expecting when a function is invoked.

As described in 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

Notice that this won't get translated into js, so it's not a real argument in the function.

Nitzan Tomer
  • 155,636
  • 47
  • 315
  • 299