Search code examples
typescriptglobal-variables

Typescript Global Variable


I'm struggling to understand the correct way to expose a variable in Typescript across multiple files. I've read a few existing questions on StackOverflow, but many seem to be for older version (1.0) of Typescript.

Given I have a project with multiple packages compiled using lerna and within the package common I want to declare a variable token which can be read/write by files in other packages, how should I do this?


Solution

  • Given that you're using modules anyway, you're likely to have much less pain using a variable exported from a module as compared to a true global variable. Because TypeScript treats imports themselves as read-only (in line with ECMAScript), you can't just export a variable and have other modules write directly to it. Instead, you can export an object and use a (writable) property of that object to hold your token. For example:

    // common/index.ts
    export const tokenHolder = {token: undefined};
    
    // another file
    import { tokenHolder } from "common";
    tokenHolder.token = "foo";
    console.log(tokenHolder.token);
    

    If this wasn't what you were looking for, please clarify the question.