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.