Reputation: 1
I don't understand why doesn't typescript compiler classify undefined
with unassigned
variable.
class MyClass {
N1: number;
N2: number;
}
var mc = new MyClass();
mc.N2 = mc.N1;
alert(mc.N2); // output: undefined
Why isn't the output Use of unassigned variable 'mc.N1'
?
It cannot be undefined
because I've defined clearly. It's a number (a number exactly without a default value).
Also, undefined
mean: we don't have variable mc.N2
.
My question is: Do I misunderstand something? If yes, please correct me.
Upvotes: 2
Views: 1818
Reputation: 22382
You misunderstand the meaning of the undefined. It does not mean that the property was defined in code. Lets read directly from MDN:
A variable that has not been assigned a value is of type undefined.
See here for more info undefined
And this is exactly what happened in your code. The value of the mc.N1 has never been assigned.
Hope this helps.
Upvotes: 2
Reputation: 7650
Here is your code in javascript:
var MyClass = (function () {
function MyClass() {
}
return MyClass;
})();
var mc = new MyClass();
mc.N2 = mc.N1;
alert(mc.N2);
Why isn't the output Use of unassigned variable 'mc.N1'?
There is not a such state unassigned in javascript.
It cannot be undefined because I've defined clearly. It's a number (a number exactly without a default value).
In javascript, a variable is eiter undefined which is not assigned any value,
or null which is a value as well, or any string, ingeger or float, date or bool.
however declaring number
has no effect on the value of variable. it is typescript internal affair.
Also, undefined mean: we don't have variable mc.N2.
Undefined does not mean, you don't have variable, it means mc.N2 a variable with has assigned no value yet
Upvotes: 2