3

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.
Kunie
  • 107
  • 2
  • 7

1 Answers1

3

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?

Senthil
  • 2,156
  • 1
  • 14
  • 19
  • 1
    Thank you. I solved. In my case, `import * as winston from 'winston'; declare global { namespace NodeJS { interface Global { log: typeof winston.Logger; } } const log: winston.Logger; }` – Kunie Oct 14 '19 at 06:54
  • Thats great to hear – Senthil Oct 14 '19 at 10:03