In my current project, I am faced with the challenge of needing to implement global variables that can be accessed from any part of the codebase. While in JavaScript I could easily achieve this with something like global.users = {}
, TypeScript presents some hurdles in this regard. As a workaround, I had to make modifications to the interface of the global
variable. After conducting some research, I attempted to address this issue by adding the following code to a file named global.d.ts
:
// global.d.ts
declare module NodeJS {
interface Global {
users: {[key: string]: import("./src/server/classes/User").User}
}
}
Although this modification resolved the Intellisense errors in VS Code, I encountered new errors when running ts-node
:
TSError: ⨯ Unable to compile TypeScript:
src/server/index.ts:22:8 - error TS2339: Property 'users' does not exist on type 'Global & typeof globalThis'.
global.users = {};