1

I have found this strange case in my NodeJS project. I will try to describe my problem here believing that there's a simple option in tsconfig.json exactly for this case. I use TypeScript v1.7.3.

File test1.ts contains variable declaration:

// test1.ts
let a = 1;

File test2.ts contains improper variable usage:

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

tsconfig.json looks like this:

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

Compiler does not throw an error to me that I am using undeclared variable a. But if I try to export some other variable, say b we will get expected error:

// 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.

1 Answer 1

1

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.

One workaround is to just add a

export {};

statement to your files.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, we've figured that on our own. Strange that there's no option for compiler to disable that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.