Akcore
Akcore

Reputation: 149

Use Global Variable In Same File As It's Declared?

Is it possible to use a global variable in the same file that it is declared?

The following code does not throw a compiletime error:

declare global {
  const something = "something goes here";
}
export default {
  somethingElse: something + " else"
}

However, it seems to be causing an 'undefined variable' error in the same file and every other file I use it in.

Upvotes: 2

Views: 179

Answers (1)

futur
futur

Reputation: 1853

TypeScript's declare syntax is used to declare variables that already exist globally in the context of a module. For instance, in a web application where variables might be coming from <script> tags that TypeScript isn't aware of, said variables and their types can be declared so that their use can be type checked.

Therefore, TypeScript wouldn't warn you about something being undefined, as it expects the variable to already have been declared elsewhere, and your declare global {} block to be informing it of said declaration.

Upvotes: 2

Related Questions