Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export existing namespace as another module

Tags:

typescript

Let's say I have a module that declares a namespace with some properties. For example:

declare module "database" {
  export namespace Database {
    namespace statics {
      type static1 = any;
      type static2 = any;
    }
  }
  const database: Database;
  export default database;
}

I can use import { Database } from "database" and then use Database.statics.static as a type.

I want to create another module that will allow you to import the statics directly. For example: declare module "database/statics"

I want to avoid rewriting all of the type definitions as there may be a lot more than in my example. I have tried moving the module definitions out, but then I'm not sure how to do something like:

declare namespace Database { ... }
declare module "database/statics" {
  export = Database.statics;
}

The above gives me Property 'statics' does not exist on type 'Database'.

I guess the sum of my question is essentially: is there any way to export a namespace from a module that is declared in another module?

like image 294
Explosion Pills Avatar asked Apr 21 '26 02:04

Explosion Pills


1 Answers

If I understand your question correctly, the answer is to use a triple slash reference directive to tell typescript to import definitions from another file/module:

database.d.ts:

declare module "database" {
    export namespace Database {
        namespace Statics {
            export type static1 = any;
            export type static2 = any;
        }
    }
}

database-static.d.ts:

///<reference path="database.d.ts"/>

declare module "database-statics" {
    import {Database} from "database";
    import Statics = Database.Statics;

    export = Statics;
}

The above example works with those two .d.ts files in the same directory. If you split those out into separate modules, you would use a ///<reference types="database"/> instead.

One thing to note is that this will make the two modules dependent on each other, so you really aren't accomplishing much by exporting the definitions from a second module.

import * as Statics from "database-statics";

Would be no different from

import {Database} from "database";
import Statics = Database.Statics;

and the two modules containing your two .d.ts files would both need to be present in the first case

like image 188
Ben Avatar answered Apr 23 '26 00:04

Ben



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!