Typescript - How to declare global variables on node.js

Viewed 3882

How to declare some custom variables globally?

Usage Example

import './logger'; // custom module: Global logger is initialized. (using winston)

log.info('This is custom global logger.'); // access to log variable globally.
1 Answers

In TypeScript, declare global block's are used to describe to add a variable to global namespace or declare a global variables.

Node.js

import * as io from 'socket.io';

declare global {
  namespace NodeJS {
    interface Global {
      SocketServer: io.Server
    }
  }
}

global.SocketServer = io.default();

Note : Global variables are fine in some cases, even with multiple processes. Its recommended / commonly used when we have want to store a constant values, example some email ids during failures ex. global.support_email = "somedl@domain.com"

Ref might be duplicate:

How to use global variable in node.js?

How to create writable global variable in node.js typescript (Using Typescript)

How to use global variable in node.js?

Related