I need to have some strongly-typed global variables.
As mentioned here: Extending TypeScript Global object in node.js, in order to add fields to the global
variable I need to add a .d.ts file that extends the Global
interface that's specified in node.d.ts.
Also, as Basarat mentioned:
Your file needs to be clean of any root level import or exports. That would turn the file into a module and disconnect it from the global type declaration namespace.
Now, I need to have fields on the Global
interface whose types are custom interfaces that I created:
declare namespace NodeJS{
interface Global {
foo: Foo
bar: Bar
}
}
I'm extremely not willing to use the any
type.
I can move/copy all the interface declarations to this declaration file, but it's a bad solution for me, since both Foo and Bar in turn, aggregate many fields of other interfaces, including third party interfaces like Moment etc.
I need a solution for this paradox
Here's an approach. I don't know if this is the 'correct' way of doing things, but it works for me with TypeScript 3.7.4.
src
, create a new folder src/types
and create a file global.d.ts
in this folder.import { Express } from 'express';
declare global {
namespace NodeJS {
interface Global {
__EXPRESS_APP__: Express;
}
}
}
declare namespace NodeJS {
interface Global {
__CONNECTION_COUNT__: number;
}
}
global.d.ts
file (and any other files you might add to src/types
) is picked up by the TypeScript compiler, by adding the following to your tsconfig.json
file:{
"paths": {
"*": ["node_modules/*", "src/types/*"]
}
}
// Below, `app` will have the correct typings
const app = global.__EXPRESS_APP__;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With