Typescript

Understanding Global Variables in TypeScript: A Beginner’s Guide

Understanding Global Variables in TypeScript: A Beginner’s Guide

Hey there, fellow TypeScript enthusiasts! Today, I want to share something that often confuses newcomers to TypeScript: working with global variables. Don’t worry, I’ve been there too, and I’m here to help you to make global variables in Node.js using TypeScript and make sure the types are correct.

Prerequisites: VSCode and TypeScript should be already installed.

Let’s start with the basics:

What are Global Variables?

Global variables are variables that can be accessed from anywhere in your code. They’re super useful when you need to share data across different parts of your application.

Setting Up Global Variables in TypeScript

First things first, let’s create a file called global.d.ts in the root of your project. This is where we’ll declare our global variables:

declare global {
    var Config: {
        Foo: string;
    };
    var Foo: string;
}

export {};

A couple of important notes here:

  1. We use var instead of let or const. This is a TypeScript quirk for global variables.
  2. The export {}; at the end is crucial. Without it, TypeScript treats this file as a script instead of a module, which can cause issues.

Now, in your index.ts file, you can use these variables like this:

global.Config = { Foo: "Bar" };
global.Foo = "Bar";

Compiling Your TypeScript Code

Make sure your tsconfig.json file includes the right files:

{
  "include": [
    "src/**/*.ts",
  ],
  "exclude": [
    "node_modules",
    "<node_internals>/**",
    "bin/**"
  ]
}

To compile, just run this command in your terminal:

tsc -b -v

Running Your Code

From the Terminal

You can run your TypeScript directly using:

node -r ts-node/register/transpile-only src\index.ts

In Visual Studio Code

Create a launch.json file in your .vscode folder with this configuration:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Debug TypeScript",
      "type": "node",
      "request": "launch",
      "args": ["${workspaceRoot}/src/index.ts"],
      "runtimeArgs": ["-r", "ts-node/register/transpile-only"],
      "cwd": "${workspaceRoot}",
      "protocol": "inspector",
      "internalConsoleOptions": "openOnSessionStart",
      "env": {
        "TS_NODE_FILES": "true"
      }
    }
  ]
}

Now you can debug by pressing F5 or selecting “Debug TypeScript” from the debug menu.

A Real-World Example: Global Logger

Let’s create a global logger. First, update your global.d.ts:

type Logger = {
    Info: (message: string) => void
}

declare global {
    var Foo: string;
    var log: Logger;
}

export {};

Then in your index.ts:

import * as Logger from './logger';

global.log = Logger;
log.Info("System booting...");
global.Foo = "Bar";
log.Info("System boot complete!");

And in logger.ts:

export function Info(message: string) {
    console.log(`${new Date().toISOString()} Log: ${message}`);
}

A Word of Caution

Be careful when using global variables in imported files. Code at the root of a file runs when it’s imported, which can lead to issues if you’re trying to use a global variable before it’s initialized.

Bonus: Modifying Global Variables for Express

If you’re using Express, you might want to add properties to the global Request object. Here’s how:

In global.d.ts:

import "express";

declare global {
    namespace Express {
        interface Request {
            token: string,
            UserID: string
        }
    }
}

export {};

And there you have it! You’re now equipped to handle global variables in TypeScript like a pro. Remember, while global variables can be useful, it’s generally best to use them sparingly. Happy coding!

Suggested Articles

Leave a Reply

Your email address will not be published. Required fields are marked *