Stephan G
Stephan G

Reputation: 3477

How to efficiently use nested modules in Typescript

Consider the following source typescript file "src.ts":

export module moduleA {
    export enum enumA {
        val1 = 0,
        val2 = 1
    };
};

export module moduleB {
    export module moduleC {
        export enum enumC {
            val3 = 0,
            val4 = 1
        };
    };
};

And consider the following file as consumer in the same folder:

import { moduleA, moduleB } from "./src";

const A: moduleA.enumA = moduleA.enumA.val1;

const B: moduleB.moduleC.enumC = moduleB.moduleC.enumC.val3;

This works just fine, even if a little verbose. But now to try to address the "verbose"-ness of this situation and make the code easier to read, I want to do something like:

import { moduleB.moduleC.enumC as enumC } from "./src";

const C: enumC = enumC.val3;

But this is a compiler error -- "Module has no exported member moduleC".

Except actually it does!

In my case I would sometimes like to go even a couple of levels deeper into nested modules, and if I am willing to write them out in all their dereferencing glory with every use, no problem. But I can't figure out how to dereference into the nest in the import statement. Is this even possible?

Upvotes: 6

Views: 8109

Answers (1)

basarat
basarat

Reputation: 276269

Is this even possible?

Use the import keyword differently to move a type:

import { moduleA, moduleB } from "./src";    
import enumC = moduleB.moduleC.enumC;

Upvotes: 8

Related Questions