Zach
Zach

Reputation: 3207

Typescript Child Namespaces and Ambient Modules

I've got a conundrum for you. I'm fairly new to Typescript, but I've enjoyed the experience thus far. Wanting to be a good developer and logically group my modules into namespaces I've come across a rare? issue. Here's the simplest example to recreate the problem.

Lets say you got a class... we'll call it ClassA, which references a class aptly named ClassB which resides in a child namespace.

namespace Foo {
    export class ClassA {
        public classB: Bar.ClassB;
        public constructor() {

        }
    }
}

and

namespace Foo.Bar {
    export class ClassB {
        public constructor() {

        }
    }
}

Typescript couldn't be happier with this. Well when I want to import things for ClassA, I'll put it inside the namespace like so:

namespace Foo {
    import SomeClass = SomewhereElse.SomeClass;
    export class ClassA {
        public classB: Bar.ClassB;
        public constructor() {

        }
    }
}

Again... we cool. But what if I wanted to import an ambient module?

namespace Foo {
    import * as SockJS from "sockjs-client"; // TS1147 GRUMBLE! CAN'T DO DAT HERE!
    export class ClassA {
        public classB: Bar.ClassB;
        public constructor() {

        }
    }
}

Ok, that's fine. I'll just move it outside the namespace like it's telling me to.

import * as SockJS from "sockjs-client";

namespace Foo {
    export class ClassA {
        public classB: Bar.ClassB; // TS2503:Now you're just a Bar that I used to know
        public constructor() {

        }
    }
}

Suddenly Typescript gets amnesia and doesn't know what Bar is. It doesn't recognize child namespaces. I've tried several ways to make it remember like nesting the namespaces or exporting them, but nothing will make it recognize this. What's the dilly yo? Any of you cool cats know what's going on or how I can resolve it and keep my child namespaces?

Upvotes: 1

Views: 1018

Answers (1)

basarat
basarat

Reputation: 275917

Suddenly Typescript gets amnesia and doesn't know what Bar is. It doesn't recognize child namespaces. I've tried several ways to make it remember like nesting the namespaces or exporting them, but nothing will make it recognize this. What's the dilly yo

Its because namespaces are global. And modules are modular. So as soon as you import a module into your file, your file becomes a module. https://basarat.gitbooks.io/typescript/content/docs/project/modules.html

Suggestion

Please use modules. There are plenty of reasons : https://github.com/TypeStrong/atom-typescript/blob/8d43dd1b930a6df0ce62454a1560acfb7eee24c9/docs/out.md

Upvotes: 2

Related Questions