1

I have a variable defined like this:

(global as any).State = {
  variables: {},
};

My question is, how do I declare the type signature of State? If I say (global as any).State: Something = ..., the compiler gives me an error saying ; expected.

As far as I can tell, it's the same question as this one, but it's about the window variable, not the global variable: How do you explicitly set a new property on `window` in TypeScript?

ford04
  • 66,267
  • 20
  • 199
  • 171
Daniel Kaplan
  • 62,768
  • 50
  • 234
  • 356
  • I think, `; expected` has rather something to do with [JS ASI](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Automatic_semicolon_insertion). Try to insert a semicolon before above code snippet and it also should work (though without strong types). – ford04 Mar 21 '20 at 09:41

1 Answers1

1

global is the Node.JS equivalent of window and a global variable declaration contained in @types/node:

// @types/node/globals.d.ts
declare var global: NodeJS.Global;
Augment global from inside a module file:
export {}

declare global { // declare global is TS specific, it is not the Node global!
  namespace NodeJS {
    interface Global {
      State: {
        variables: {}
      }
    }
  }
}
Augment global from inside a script file (without export/import):
declare namespace NodeJS {
  interface Global {
    State: {
      variables: {}
    }
  }
}

You will then be able to set State without relying on any:

global.State = { variables: {} }
Community
  • 1
  • 1
ford04
  • 66,267
  • 20
  • 199
  • 171