If I want to export all the exported members of a module (including code), I can use
export * from 'module'
If I want to export the type of a class without code I can do
export type {typeName} from 'module'
Now I have a need to export all the types from a module, without code. I would be tempted to do
export type * from 'module'
as that's the intuitive thing, but typescript type exports must be named exports (ts 1383).
So how I can I export everything from a module in such a way that its members cannot be used at runtime?
Workarounds I can think of:
Get over it and use export *
. This is an option. But for our use case I don't want users of our library to use these classes, only to use them to annotate their types
Ask pretty-please that everyone who uses our library please use import type {typeName} from 'myLibrary'
. I guess this is an option too, but how do I convince users to do this?
tl;dr: How can I emulate global type exports in Typescript?
Use a named export to export a type in TypeScript, e.g. export type Person = {} . The exported type can be imported by using a named import as import {Person} from './another-file' . You can have as many named exports as necessary in a single file.
TypeScript supports export = to model the traditional CommonJS and AMD workflow. The export = syntax specifies a single object that is exported from the module. This can be a class, interface, namespace, function, or enum.
Use named exports to export a function in TypeScript, e.g. export function sum() {} . The exported function can be imported by using a named import as import {sum} from './another-file' . You can use as many named exports as necessary in a single file.
Use named exports to export multiple classes in TypeScript, e.g. export class A {} and export class B {} . The exported classes can be imported by using a named import as import {A, B} from './another-file' . You can have as many named exports as necessary in a file.
As stated in your referenced pull request, wildcard reexporting of types is not yet implemented (and may never). Hence reexporting all types to the root level is currently not possible. The closest you can get is by wrapping the reexported types in their own named collection:
// your-module
import type * as Types from "external-module";
export { Types };
// Usage by the end user
import { Types } from "your-module";
let a:Types.Class;
The drawback of this approach is that the user is not able to import the types independently like import { Class } from "your-module";
. The types are exported as type only though, so this would still have no effect on the size of your bundle and one still can't instantiate the exported types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With