valepu
valepu

Reputation: 3315

How to correctly import the same namespace in two different files in Typescript

I'm having an issue in understanding how to make two files with the same namespace and import one into the other in Typescript.

This is the situation:

file1.ts

export namespace nspace {
    export class ClassA {

    }
}

file2.ts

import {nspace} from './file1';

export namespace nspace {
    export class ClassB extends nspace.ClassA {
        private z: nspace.ClassA;
    }
}

inside file2 i have these errors:

1) Individual declarations in merged declaration 'nspace' must be all exported or all local

2) Property 'ClassA' does not exist on type 'typeof nspace'

On top of that, ClassA is correctly found when used to declare the type of the z field (it even brings me to the correct file if i use "go to declaration" in my IDE)
I have tried searching the first error on the internet because i don't really understand what it means but none of the pages i found helped. I read the documentation about Declaration Merging in Typescript but i couldn't find a situation similar to mine
I don't know if this is of any help but i'm using SystemJS in my application

Upvotes: 2

Views: 3805

Answers (2)

valepu
valepu

Reputation: 3315

Apparently, giving another name when importing worked:

file1

export namespace nspace {
    export class ClassA {

    }
}

file2

import * as a from './file1';

export namespace nspace {
    export class ClassB extends a.nspace.ClassA {
        private  b: a.nspace.ClassA;

    }
}

Upvotes: 2

Ward D.S.
Ward D.S.

Reputation: 558

It should be much simpler to use:

ClassA.ts
namespace MyApp {
    export class ClassA {
        public a: string = "classA";
    }
}
ClassB.ts
namespace MyApp {
    export class ClassB extends ClassA {
        private class_a: ClassA = new ClassA();
        private b: string = "classB";
    }
}
main.ts
namespace MyApp {
  var b = new ClassB();
  console.log(b.class_a.a) // "classA"
}

The compiler will recognize that you are working within the same namespace, so there is no need to import it, or even prefix it.

It might be necessary to add a reference to the top of the ClassB.ts file as such: /// <reference path="ClassA.ts" />

Although in my setup, I haven't had to do this, the compiler seems to pick things up correctly automatically. (I use a single OutFile and the exclude directive in tsconfig.json)

Sidenote:

What I find strange in this is that you are forced to export ClassA for it to be discovered in my ClassB.ts. It seems impossible to keep ClassA and ClassB private to the namespace if I want to use them in Main.ts (even in private variables). It simply errors with "Can not find name..."

Upvotes: 2

Related Questions