简体   繁体   English

TypeScript编译器不会在缺少声明时引发错误

[英]TypeScript compiler does not throw error on missing declaration

I have found this strange case in my NodeJS project. 我在NodeJS项目中发现了这种奇怪的情况。 I will try to describe my problem here believing that there's a simple option in tsconfig.json exactly for this case. 我会在这里描述我的问题,因为tsconfig.json中有一个简单的选项正好适合这种情况。 I use TypeScript v1.7.3. 我使用TypeScript v1.7.3。

File test1.ts contains variable declaration: 文件test1.ts包含变量声明:

// test1.ts
let a = 1;

File test2.ts contains improper variable usage: 文件test2.ts包含不正确的变量用法:

// test2.ts
console.log(a);

tsconfig.json looks like this: tsconfig.json看起来像这样:

// tsconfig.json
{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es5"
  }
}

Compiler does not throw an error to me that I am using undeclared variable a . 编译器不会抛出一个错误,我认为我使用未声明的变量a But if I try to export some other variable, say b we will get expected error: 但是,如果我尝试导出其他变量,请说b我们将得到预期的错误:

// test1.ts
let a = 1;
export let b = 2;

Compiler: 编译:

Error:(1, 13) TS2304: Cannot find name 'a'.

How can I make compiler emit an error in the first case? 在第一种情况下,如何使编译器发出错误? I've just found out in my project that I suddenly removed a variable and it failed in runtime , not compile time . 我刚刚在项目中发现我突然删除了一个变量,并且该变量在运行时失败,而不是在编译时失败。

This is an unfortunate consequence of the fact that files without some kind of export or import are considered "script" files by the compiler. 这是不幸的结果,因为编译器将没有某种类型的导出或导入的文件视为“脚本”文件。 The compiler assumes script files just operate in the global scope, and will just get stitched together. 编译器假定脚本文件仅在全局范围内运行,并且将被缝合在一起。 Without --outFile being specified, it won't be able to definitely say whether a variable declaration will occur after its usage. 如果不指定--outFile ,将无法肯定地说出变量声明在使用后是否会发生。

One workaround is to just add a 一种解决方法是仅添加一个

export {};

statement to your files. 对文件的声明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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