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.
2

1 Answer 1

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 = "[email protected]"

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?

Sign up to request clarification or add additional context in comments.

2 Comments

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; }
Thats great to hear

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.