Search code examples
typescriptduktape

How can I replace the type of self in TypeScript?


I'm working in an embedded JavaScript engine (based on duktape). In this context, "self" is not of type Window but either of type Script or JSComponent. Using typescript, compilation causes errors when using members of these classes on self.

For this reason, I need to be able to redeclare self as a JSComponent or Script. Digging around in the standard TypeScript libraries, I stumbled on the following, which I've found no documentation on anywhere:

/// <reference no-default-lib="true"/>

Adding this to a d.ts to be included half solves the problem:

/// <reference path="./Atomic.d.ts" />
/// <reference no-default-lib="true"/>

// Redeclare self as a JSComponent
declare var self: Atomic.JSComponent;

I can now reference this in my TS files, and use self as a JSComponent. However I can no longer use standard classes such as Object and Array-in this or any other TS file in my project.

Is there a way to use no-default-lib for just this section of code, to replace the definition of self? Alternatively, is there another way to achieve this re-declaration?


Solution

  • Is there a way to use no-default-lib for just this section of code, to replace the definition of self? Alternatively, is there another way to achieve this re-declaration?

    TIP * recommend using a tsconfig.json with compilerOptions.noLib set to true, instead of this magic comment

    Answer

    Compile with noLib set to true and a custom copy of lib.d.ts copied from the TypeScript repo.

    Topic covered here : http://basarat.gitbooks.io/typescript/content/docs/types/lib.d.ts.html