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.

2
  • Would this help? Commented Aug 29, 2020 at 22:15
  • I saw that “declare global” trick, but you have to write the signature twice. Commented Aug 29, 2020 at 22:16

1 Answer 1

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 = () => {};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.