[英]using module inside a module for type declaration doesn't compile (TS2503 cannot find namespace)
I'm getting a compilation error when I try to do this in typescript (TS2503 cannot find namespace): 我在打字稿中尝试执行此操作时遇到编译错误(TS2503无法找到名称空间):
import mylib = require("./mylib");
let person: mylib.Person = new mylib.Person("A");
where I have a mylib
directory with two files: 我有一个带有两个文件的
mylib
目录:
$ cat mylib/index.ts
import Person = require("./Person");
export = { Person: Person }
$ cat mylib/Person.ts
export = class Person{
name: String;
constructor(name) {
this.name = name;
}
}
The problem is with the type declaration let person: mylib.Person = new mylib.Person("A");
问题在于类型声明
let person: mylib.Person = new mylib.Person("A");
. 。 If I replace it with
let person = new mylib.Person("A");
如果我将其替换为
let person = new mylib.Person("A");
, it does compile, but I want to declare the type explicitly. ,它确实可以编译,但是我想显式声明类型。 At the same time, I want to avoid importing
mylib/Person
. 同时,我想避免导入
mylib/Person
。 So I want to avoid this solution: 所以我想避免这种解决方案:
import Person = require("./mylib/Person");
let person: Person
I decided to put everything in mylib
to have a single point of access and eliminate the need to import each individual submodule. 我决定将所有内容放在
mylib
以具有单个访问点,而无需导入每个单独的子模块。 What's an alternative way to solve the compilation error? 解决编译错误的另一种方法是什么? Ideallly, I'd access
Person
through a previously imported mylib
module. 理想情况下,我将通过先前导入的
mylib
模块访问Person
。
That is a very interesting approach, but the problem is that you can't use types like that (as properties of an object). 这是一种非常有趣的方法,但是问题是您不能使用这样的类型(作为对象的属性)。
Instead, you could do this: 相反,您可以这样做:
import { Person } = require("./mylib");
let person: Person = new Person("A");
That way you are using object destructuring and, as you can see, is the usual way of importing classes in TypeScript. 这样,您就可以使用对象分解,并且可以看到,这是在TypeScript中导入类的常用方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.