Reputation: 5048
I declared a variable x
as
public x : 0;
Instead of initialising it to 0
Thinking that I had declared it correctly, I initialised it like
this.x = 5;
I was getting error on the above line, which read
Type '5' is not assignable to type '0'.ts(2322)
Can anybody tell, why is this happening?
Upvotes: 9
Views: 39799
Reputation: 36730
This is a feature of Typescript, after the :
the possible type(s) are declared and that could be specific values also.
For example you could also limit variables to specific strings:
var action : "email" | "sms";
In this case action = "fax"
will give a compile error.
With strings this is called "String Literal Types". With numbers this is called "Numeric Literal Types".
So in you case you declared it a numeric literal type with 0
as allowed value.
See also https://www.typescriptlang.org/docs/handbook/advanced-types.html#string-literal-types and https://www.typescriptlang.org/docs/handbook/advanced-types.html#numeric-literal-types
So beware of mixing =
and :
in Typescript, as both are correct Typescript in this case but have different behavior ;)
Upvotes: 10