6

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?

2
  • Hah, first you made nested modules, and then you argue that it is verbose : ) Why in the world you want nested modules then? Commented Apr 13, 2018 at 4:50
  • 3
    To precisely reflect domain types in a complex cascading set of namespaces on the server that get serialized into JSON objects for AJAX calls. Commented Apr 13, 2018 at 5:17

1 Answer 1

9

Is this even possible?

Use the import keyword differently to move a type:

import { moduleA, moduleB } from "./src";    
import enumC = moduleB.moduleC.enumC;
Sign up to request clarification or add additional context in comments.

2 Comments

Some further notes: This link no longer works; another answer (stackoverflow.com/a/67165362/2854555) says this behaviour is deprecated. So probably should be avoided?
Link updated. Appreciate the comment 🌹

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.