How to extend TypeScript global object in Node.js?

Sometimes, we want to extend TypeScript global object in Node.js.

In this article, we’ll look at how to extend TypeScript global object in Node.js.

How to extend TypeScript global object in Node.js?

To extend TypeScript global object in Node.js, we can add a type definition file that extends the Global interface in the NodeJS module.

For instance, we write

declare module NodeJS {
  interface Global {
    foo: any;
  }
}

in a .d.ts file in our Node TypeScript project to add the foo property into the Global interface.

Then we can use the variable without compiler errors by using global.foo.

Conclusion

To extend TypeScript global object in Node.js, we can add a type definition file that extends the Global interface in the NodeJS module.