1

I can define a global function in a non-module file:

foo.ts:

function foo() {}

I can call that function from a file bar.ts without importing foo.ts:

bar.ts:

foo(); // call global function foo

However, as soon as I import another module into foo.ts, foo.ts is turned into a module and the global definition disappears. Resulting in an error in bar.ts when trying to call foo.

How can I define a global function in a module that is global across the entire project without importing it.

EDIT:

I know about the declare global syntax, but in that case I would need to write every function signature twice: Once to declare it globally and once to bind it to globalThis. I am looking for something with less boilerplate.

user3612643
  • 5,096
  • 7
  • 34
  • 55

1 Answers1

0

It looks like declare global is really required in such a case. The only (verbose) solution I found is:

declare global {
  function foo(): void;
}

globalThis.foo = () => {};
user3612643
  • 5,096
  • 7
  • 34
  • 55