Call a global variable inside module

Typescript

Typescript Problem Overview


I have a typescript file called Projects.ts that I want to reference a global variable declared in a bootstrap plugin called bootbox.js.

I want to access a variable called bootbox from within a TypeScript classes.

Is it possible?

Typescript Solutions


Solution 1 - Typescript

You need to tell the compiler it has been declared:

declare var bootbox: any;

If you have better type information you can add that too, in place of any.

Solution 2 - Typescript

For those who didn't know already, you would have to put the declare statement outside your class just like this:

declare var Chart: any;

@Component({
  selector: 'my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.scss']
})

export class MyComponent {
    //you can use Chart now and compiler wont complain
    private color = Chart.color;
}
  

In TypeScript the declare keyword is used where you want to define a variable that may not have originated from a TypeScript file.

It is like you tell the compiler that, I know this variable will have a value at runtime, so don't throw a compilation error.

Solution 3 - Typescript

If it is something that you reference but never mutate, then use const:

declare const bootbox;

Solution 4 - Typescript

Sohnee solutions is cleaner, but you can also try

window["bootbox"]

Solution 5 - Typescript

If You want to have a reference to this variable across the whole project, create somewhere d.ts file, e.g. globals.d.ts. Fill it with your global variables declarations, e.g.:

declare const BootBox: 'boot' | 'box';

Now you can reference it anywhere across the project, just like that:

const bootbox = BootBox;

Here's an example.

Solution 6 - Typescript

// global.d.ts
declare global {
  namespace NodeJS {
    interface Global {
      bootbox: string; // Specify ur type here,use `string` for brief
    }
  }
}

// somewhere else
const bootbox = global.bootbox
// somewhere else
global.bootbox = 'boom'

Solution 7 - Typescript

Download the bootbox typings

Then add a reference to it inside your .ts file.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1027303View Question on Stackoverflow
Solution 1 - TypescriptFentonView Answer on Stackoverflow
Solution 2 - TypescriptHimanshu AroraView Answer on Stackoverflow
Solution 3 - TypescriptJosh WulfView Answer on Stackoverflow
Solution 4 - TypescriptPrusdrumView Answer on Stackoverflow
Solution 5 - TypescriptKrzysztof GrzybekView Answer on Stackoverflow
Solution 6 - TypescriptsammyView Answer on Stackoverflow
Solution 7 - Typescriptser savvView Answer on Stackoverflow