Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does typescript allow variable to be used before declaring it?

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 till this time.

If I remove the second line I get the compiler error.

I know its valid in JavaScript but I would expect TypeScript to give me compilation error or warning.

like image 977
Amitabh Avatar asked Jun 24 '13 11:06

Amitabh


1 Answers

Because hoisting behavior can be confusing. Your code actually means.

var a, b

b = a + 10
a = 10

alert(b.toString())

There are valid reasons to allow hoisting, but they don't involve var, but function - you can call function declared later.

alert(identity(i))

function identity(i) {
    return i
}

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

While I agree this case should have an warning (not error, TypeScript wants to be compatible with JavaScript), it doesn't appear that TypeScript currently notices that. Every variable in TypeScript has a type that CANNOT change during lifetime of variable, and in your case, a is number type (it isn't aware that you use it before assignment, because var sets type implicitly). TypeScript assumes it's a number, even if it's not, because of its declaration.

You may want to report this as a bug in TypeScript.

like image 125
Konrad Borowski Avatar answered Sep 20 '22 01:09

Konrad Borowski