Reputation: 8287
I have a global declaration file where I have to use an import
statement, thus making it a module, therefore for exposing global types I have to declare them over the global namespace.
Firstly I tried this:
import { SomeType } from 'some-package';
declare namespace global {
interface ShouldBeGlobal {}
}
This doesn't throw a syntax error, but it doesn't work how I'd expect: the interface ShouldBeAGlobal
is not exposed globally.
However, this works and it's exposed everywhere:
import { SomeType } from 'some-package';
declare global {
interface ShouldBeGlobal {}
}
Why doesn't the first one work?
Upvotes: 3
Views: 1363
Reputation: 8287
In the first example, you're not exposing anything to the global namespace because you're actually creating a new namespace called global
. An easy way to confirm this is by commenting your import
statement, thus making your declaration file a global declaration file (those that don't have import
/export
), and try to access global.ShouldBeGlobal
—you'll see that it's available.
The second way is the correct way to expose types into the global namespace (the real one). Similarly as above, if you want to understand what the namespace global
statement is actually doing, you can also change it to this:
import { SomeType } from 'some-package';
declare global {
interface ShouldBeGlobal {}
// not that you don't need the declare keyword here again, because it's already nested on a declare block
namespace global {
interface AnotherInterface {}
}
}
Now in any file you should still be able to access the ShouldBeGlobal
interface, but now you also have global.AnotherInterface
, because now you created a new namespace called global
inside the global namespace.
Upvotes: 2