Rafael
Rafael

Reputation: 577

Allow for certain "unfound" variable names in typescript?

The module I'm using is supposed to be called in browser as a good old Window object, therefore not being imported into files as a module. For that reason Typescript's compiler freaks out with the "Cannot find name [variable]". Is there a way I can "whitelist" a name that Typescript can't find but I'm sure it will be used at runtime?

Upvotes: 3

Views: 1300

Answers (2)

Nathan Friend
Nathan Friend

Reputation: 12834

Try:

declare var yourVariableName: YourType;

At the top of the file where you use yourVariableName. This indicates to the TypeScript compiler that this global variable will exist at runtime.

Upvotes: 6

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250266

You can declare any number of variables and extra properties on the window object so that typescript knows about them, but does not emit any code for them. You can even add a type annotations to describe their runtime behavior of these Javascript objects or you can use any if you don't mind going untyped.

declare var someGlobalVar: any;
declare var someGlobalTypedVar: { 
    doSomething(): number
};

interface Window {
    someCustomWindowProp: any
}

window.someCustomWindowProp = 10 // works

You can declare global variables, you can add to existing interfaces, such as Window or Document depending on your needs.

Upvotes: 1

Related Questions