简体   繁体   中英

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!

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+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM