I declare a global variable in typescript something like: global.test = "something" I try to do that I get the error property ‘test’ does not exist on type ‘Global’.
Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword.
The type syntax for declaring a variable in TypeScript is to include a colon (:) after the variable name, followed by its type. Just as in JavaScript, we use the var keyword to declare a variable. Declare its type and value in one statement.
A global variable is a variable that is defined in the main script. In the following example, var c=10; in the main script is a global variable.
I try to do that I get the error property ‘test’ does not exist on type ‘Global’.
Create a file globals.d.ts
with
interface Global {
test: string;
}
Declaration files : https://basarat.gitbook.io/typescript/docs/types/ambient/d.ts.html
in global.ts
export namespace Global {
export var test: string = 'Hello World!';
}
in your.ts
import { Global } from "./global";
console.log(Global.test)
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