Global Variables

Is there a good way to access global variables? It is difficult to manage the state of a variable that cannot be passed between views. My exact use case is a TCP Socket object in a TypeScript app.

My solution was to create a new app module with the file type as index.d.ts.

After that, I created a namespace within the file named global

declare namespace global {
    var variable;
}

I then can access this variable anywhere in the app with similar code below.

// @ts-ignore
global.variable = 1;

Notice @ts-ignore above the variable. This has to be there otherwise the IDE will throw an error and prevent you from building. It’s not best practice to utilize // @ts-ignore as it ignores the linting error. However, after testing, the IDE linter seems to be giving a false negative. Utilizing the namespace does not negatively affect the program. It is a bit annoying to have to place the // @ts-ignore comment above each namespace usage, but it does work.

This would be a great feature to have. I’ve already put it as a suggestion on the roadmap. Global variables that persist among views can be helpful.

@alex-valdez The recommended approach for global variables in TS apps is as follows:

  1. Create an app module called e.g. “global”
  2. You can export both functions and variables here with e.g. export var myVar: myType
  3. In the view where you want to use this, import with import * as global from "/lib/global"
    (this does requires an import statement, but at the same time it makes it explicit where the global variable is being pulled from)

Another option which is probably a bit cleaner and closer to your code would be to:

  1. Change declare namespace global in your code to simply declare global
  2. Then, in your code, change global.variable to self.variable

This will enable you to remove the @ts-ignore

Thank you @kobie !

I actually needed to do option 2 which is declaring the namespace. Option 1 seemed to not work because it would not persist across views. I’m specifically using the global variable to store a TCP socket connection.

Also, I discovered the reason for having to put @ts-ignore in my case. My lib file with my namespace looks similar to the following

import { CreatedClass } from '~/lib/CreatedClass';

declare namespace global {
        var variable: CreatedClass;
}

This was so I could use TypeScripts features of the compiler knowing that variable is of type CreatedClass. For whatever reason, this caused the linting error. Anywhere I use global.variable I had to include the @ts-ignore. Unless I assigned it to another variable like the following.

// @ts-ignore
var variable = global.variable;

// now free to use variable anywhere without the // @ts-ignore

If I changed the data type of variable in the namespace to a not imported type such as any, then I did not have to use @ts-ignore.

I will try using declare global instead of declare namespace global.

Thanks again for the help!