Typescript: Unable to use global this when `noImplicitThis` is enabled.

Created on 5 May 2017  路  6Comments  路  Source: microsoft/TypeScript



When noImplicitThis is turned on, you are unable to reference the global this (which may be window, or global, or other value in various runtime environments).

I'm not sure if there is a recommended way around this, but currently there does not appear to be a way to get the "global" this without an error 'this' implicitly has type 'any' because it does not have a type annotation. This may be something I'm just not seeing. I tried to define global but that wasn't much help.

TypeScript Version: 2.3.x

Code

(function (this: any, root) {
    // do something isolated 
})(<any>this);

Expected behavior:
Be able to use the global this without error.

Actual behavior:
Compiler error 'this' implicitly has type 'any' because it does not have a type annotation. when using this globally.

cc @benlesh

Awaiting More Feedback Suggestion

Most helpful comment

The intention here was to not allow use of this in the global scope with --noImplicitThis since there is no way of declaring the type of this globally.

All 6 comments

The intention here was to not allow use of this in the global scope with --noImplicitThis since there is no way of declaring the type of this globally.

From my response in #3576 which was adapted from this Stack Overflow answer, you could just use Function("return this")();

Function("return this")()

Ugh.

Can TypeScript start taking a serious look at the global keyword which is stage 3 now?

tracked by https://github.com/Microsoft/TypeScript/issues/12902 and https://github.com/Microsoft/TypeScript/issues/14052

Also the proposal seems to have stalled on the choice of the variable name; since global breaks existing code.

It appears a variable name was chosen (globalThis) and has successfully shipped in Chrome 71 stable channel. https://www.chromestatus.com/features/6571514765770752

Fixed by #29332

Was this page helpful?
0 / 5 - 0 ratings