Skip to content

Export a TypeScript class from another file than it has been defined in #10058

Closed
@loilo

Description

@loilo

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions