Typescript 不会抱怨缺少导入

Shi*_*yal 6 typescript

脚.ts的内容:

let a: Person = new Person();
Run Code Online (Sandbox Code Playgroud)

bar.ts 的内容:

class Person {}
Run Code Online (Sandbox Code Playgroud)

tsconfig.json 文件包含由tsc --init.

我正在使用打字稿版本 2.6.2。

上面的代码简单地编译,没有关于Person未定义的错误。如果我在 foo.ts 中重命名PersonPersons,那么它确实会抛出一个错误,说cannot find name 'Persons'. 所以就好像它以某种方式自动导入这个文件。

另请注意,我没有Person在 bar.ts 中导出该类。如果我确实添加了导出语句,那么一切都会按照它应该的方式运行 - 我收到一条错误消息,说cannot find name 'Person'.

有谁知道这里发生了什么?这是用户错误吗?

编辑:

也许这在浏览器中有意义,但对我来说这种行为在 node.js 应用程序中没有意义。是否有禁止这种行为的 Typescript 标志?

Shi*_*yal 3

编译器标志--isolatedModules将确保所有 .ts 文件都是模块。一旦你通过添加 1或来创建foo.ts和模块,那么该类将不再是全局的。bar.tsimportexportPerson

但这并不能解决以下类似问题: https://github.com/Microsoft/TypeScript/issues/18232#issuecomment-359200157