This is a question I first asked on StackOverflow but apparently nobody actually knows. I'm posting it here because it looks like a quite common scenario which I think is either already achievable somehow (which then should be in the docs in my opinion) or impossible on purpose for which the design-wise reasons would be interesting.
I wrote a small library in TypeScript and I've been trying to export its classes in a single place. The goal here is to make the classes available to a browser via a (nested) global object represented by nested TypeScript namespaces. My goal on the other hand is for each class to be agnostic of how they are made available to the outside.
Let's assume I've got a class Foo
// lib/foo.ts
export class Foo {}
Now I want to make this available to whoever uses the package via the MyModule
namespace defined in another file. How would I achieve this? I thought of two potential solutions to this, but both do have their downsides which makes them basically useless.
I could define a variable and assign the class to it:
// api.ts
import { Foo as MyFoo } from "./lib/foo";
export namespace MyModule {
export const Foo = MyFoo;
}
This will in fact allow me to create instances of the class from an external place like new MyModule.Foo
but won't give me the possibility to use them as types since then
import { MyModule } from "path/to/module/api";
let myFooInstance: MyModule.Foo;
will throw a TypeScript error stating that
Module "path/to/module/api" has no exported member 'Foo'
The other way around I tried to use export type Foo = MyFoo
instead of const
and while this is usable as a type I obviously can't instantiate the class since it's just an alias.
So: Is it generally possible to export classes from namespace in a third place, did I overlook a certain practice for this or is this not possible by design?
The other way around I tried to use export type Foo = MyFoo instead of const and while this is usable as a type I obviously can't instantiate the class since it's just an alias.
You can do both:
export const Foo = MyFoo;
export type Foo = MyFoo;
...and now I feel a bit dumb. Thank you, would've never thought how easy it could be.
Is it possible to do this with a namespace too?
Is it possible to do this with a namespace too?
export import N = M;
Is it possible to do it on a Generic Interface? I want to be able to export IMyInterface
let x = new MyClass
Where MyClass implements IMyInterface.
Most helpful comment
You can do both: