简体   繁体   中英

Typing `this` in TypeScript

Is there a way to set the type of this in TypeScript?

I'm sure there's plenty of uses for it, but in my particular case it's for typing a JS library, and writing a plugin for it.

For example:

// Some library
declare var SomeLib: sl.ISomeLibStatic;
declare module sl {
    interface ISomeLib extends ISomeLibApi {
        baseFn(): void;
    }

    interface ISomeLibStatic {
        new (): ISomeLib;
        API: ISomeLibApi;
    }

    interface ISomeLibApi {
    }
}

// Plugin file
declare module sl {
    // Extend the API signature declaration
    interface ISomeLibApi {
        extraFn(): void;
    }
}

module sl {
    // Implement the function
    SomeLib.API.extraFn = function () {
        // Get typing on this here
        this.baseFn();
    };
}

Anybody knows a way to do this without a variable like: var typedThis: ISomeLib = this; ?

Currently the only way I found was having cast it on every usage <ISomeLib>this which is cumbersome, and not defined in the type of the function.

There is no way to hint to the language service what context to apply to the function.

The only mechanism that will cleanly supply type checking and auto-completion without resulting in runtime artefacts is:

(<ISomeLib>this).baseFn();

Which compiles down to the desired:

this.baseFn();

It can be done as follows:

function foo(this: MyType) { 
}

You can also use this: this to enforce the function to be called on the declaring context, or this: void to prevent the usage of this.

However, the target version for this feature is TypeScript 2.0 (although it is already implemented on the latest develop).

See here for details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM