Reputation: 30929
In a TypeScript external module declaration (either an entire .d.ts
file or a declare module
block in another file), by default, all symbols are exported even if they are not marked export
. Luke Pighetti discovered that adding an export { ... }
statement suppresses this behavior, so that only symbols marked export
are exported.
Example my-module.d.ts
:
export const a = 1;
declare const b = 2;
export {};
consumer.ts
:
import { a } from "./my-module"; // OK
import { b } from "./my-module"; // Error
This behavior is potentially useful. Is it intentional, or a TypeScript bug that I should report and not encourage people to rely on?
Upvotes: 3
Views: 410
Reputation: 30929
andy-ms says the behavior is intentional. (But it's undocumented AFAIK, like so many advanced TypeScript behaviors. :( )
I tracked down the compiler code that is involved. The full list of constructs that shut off automatic export:
export { ... }
export { ... } from "module"
export * from "module"
export = ...
export default
of an expression, but not export default
of a function, class, or interface definitionUpvotes: 6
Reputation: 15589
This is intentional.
A TypeScript file can be either a script file or a module file. The differentiation between the to is that module file has at least one top-level import/export.
When a file is a module file, only the code explicitly exported with the export
keyword would be available.
For a script file, it is treated as if it is part of the global, meaning your content will be available in other files.
For typings file (*.d.ts
), in DefinitelyTyped they are written as script file with the format of declare module x { ... }
to define the typings for a specific module.
It is written that way in DefinitelyTyped because it is a repository of many modules, and the tooling needs to know which module it is defined for.
If you create a typings file for a JavaScript library and distribute it with that library, it will be written as a module file(s).
Upvotes: 0