5

I have a file a.ts which contains a class A inside a module:

module moduleA {

  export class A {
  }

}

export = moduleA.A;

And another file b.ts which imports class A:

import A = require('a.ts');

class B {

  // This leads to an error: Cannot find name 'A'
  private test: A = null;

  constructor() {
    // But this is possible
    var xyz = new A();
  }
}

Interestingly, Typescript shows an error when I want to use A as a type in B. However, instantiating A does not lead to an error.

Can anybody explain me, why this is like that? Thank you very much!

1 Answer 1

7

The use of the namespace module moduleA is not necessary... you can do this...

the keyword module is synonymous with namespace (C#) now... best practice is to use the ES6 style module structure which is basically each file is a module and export what you need and import what you need from elsewhere.

// a.ts
export class A {}

// b.ts
import { A } from './a';
class B {
  private test: A = null; // will not error now
  constructor () {
    var xyz = new A();
  }
}

Note: this is based upon TypeScript v1.5+

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks a lot for your answer! Though I need the module structure like this, because I have variables that must stay outside the class A but inside the module. Don't you think my solution should theoretically work like that?
@user986305 You should still be able to declare variables outside the class but in the same file if you do things Brocco's way.
@JKillian is correct, those variables will be contained to the scope of that file/module without being leaked externally.
Thanks JKilian and Brocco! I had it that way before with a variable "dependencies" in the various files. However, Typescript kept telling me that the variable "dependencies" was already declared with another type (in another file). Now I removed the modules as you described and it seems to work. I don't know if Typescript was not synced before or if it works now because I updated it. Anyways, to me the above problem is still not really solved to me. What do you think?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.