Global variables can be used by everyone, both inside of functions and outside.
If you want to refer to a global variable in a function, you can use the global keyword to declare which variables are global.
We can create a config file & store the entire global variable to be shared across modules or script in it. By simply importing config, the entire global variable defined it will be available for use in other modules.
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
.
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.
If it is something that you reference but never mutate, then use const
:
declare const bootbox;
Sohnee solutions is cleaner, but you can also try
window["bootbox"]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With