Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I declare a global variable in typescript

Tags:

typescript

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’.

like image 964
Jheorge Avatar asked May 23 '17 03:05

Jheorge


People also ask

How do you declare a global variable?

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.

How do I declare a variable in TypeScript?

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.

How do you define a global variable in a script?

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.


2 Answers

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;
}

More

Declaration files : https://basarat.gitbook.io/typescript/docs/types/ambient/d.ts.html

like image 121
basarat Avatar answered Oct 10 '22 02:10

basarat


in global.ts

export namespace Global {
    export var test: string = 'Hello World!';
}

in your.ts

import { Global } from "./global";
console.log(Global.test)
like image 38
nsnze Avatar answered Oct 10 '22 01:10

nsnze