Why does typescript allow the use of a variable before its declaration?

Typescript does not give a compiler error for the following code:

var b = a + 10; // Why no compilation error here var a = 10; alert(b.toString()); 

I would expect the first line to be an error, as I have not declared or initialized var a until this time.

If I delete the second line, I get a compiler error.

I know that it is valid in JavaScript, but I would expect TypeScript to give me a compilation error or warning.

+7
source share
2 answers

Assuming you understand that your code is equivalent:

 var a, b b = a + 10 a = 10 alert(b.toString()) 

This, in turn, is equivalent to:

 var a = undefined, b = undefined b = a + 10 a = 10 alert(b.toString()) 

The reason this should be allowed is because undefined is a valid value for a variable that you can assign and read.

There are various use cases when this functionality is valuable. For example, the module template used in typescript:

 module x{ export var foo; } 

Generates javascript code that uses this fact:

 var x; (function (x) { x.foo; })(x || (x = {})); //x was never assigned but used in "x ||" part 

This remains in TypeScript due to JavaScript backward compatibility (not to mention that it is useful).

Here is a pure TypeScript usecase. Perhaps you want to pass undefined to a function call ( this is really typescript ):

 var a:number = undefined; // same as simply "var a" console.log(a); 

It is assumed that the TypeScript developer wants to know the core JavaScript language.

This does not apply to languages ​​where Reading before assignment is not valid (e.g. C #). In C #, an unrecognized variable doesn't matter. In JavaScript, this is done. Therefore, TypeScript should allow this.

+5
source

Because hoisting behavior can be misleading. Actually your code.

 var a, b b = a + 10 a = 10 alert(b.toString()) 

There are good reasons for lifting, but they do not include var , but function - you can call the function declared later.

 alert(identity(i)) function identity(i) { return i } 

In this case, alert uses the result of the function declared later. Thanks to the lift, it works.

As long as I agree, this case should have a warning (and not an error, TypeScript wants to be JavaScript compatible), it doesn't seem like TypeScript is currently noticing this. Each variable in TypeScript has a type that CANNOT be changed during the lifetime of the variable, and in your case the type is a is number (it does not know that you use it before the assignment, because var sets the type implicitly). TypeScript accepts this number, even if it is not, because of its declaration.

You may report this as an error in TypeScript.

+10
source

All Articles