gizmodus
gizmodus

Reputation: 188

Typescript: 'Cannot find name' error of imported class

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!

Upvotes: 5

Views: 8621

Answers (1)

Brocco
Brocco

Reputation: 65043

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+

Upvotes: 7

Related Questions