Search code examples
typescriptglobal-variables

Property 'users' does not exist on type 'Global & typeof globalThis' although modifying global with global.d.ts


I am trying to develop a project in the one I need to include global variables that could be accessed from anywhere. Normally, with javascript I would be able to write something like this: global.users = {} but this is not that easy in typescript, therefore, I need to modify the interface of the global variable. After some research I tried including in global.d.ts the following code:

// global.d.ts

declare module NodeJS  {
    interface Global {
        users: {[key: string]: import("./src/server/classes/User").User}
    }
}

Which actually made the VS Code Intellisense errors dissappear, but when I run ts-node the errors appear again:

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 = {};

Solution

  • I tried to follow https://bobbyhadz.com/blog/typescript-declare-global-variable in order to do it. Using the module format (declare global { var users: ... }) didn't work for me, but the non-module global.d.ts did:

    declare var users: ...
    

    Make sure you don't have any import or export statement in your global.d.ts. However, import() type expression like the one you used is OK.