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?
The "Type 'string' is not assignable to type" TypeScript error occurs when we try to assign a value of type string to something that expects a different type, e.g. a more specific string literal type or an enum. To solve the error use a const or a type assertion.
The "Type 'number | undefined' is not assignable to type number" error occurs when a possibly undefined value is assigned to something that expects a number . To solve the error, use the non-null assertion operator or a type guard to verify the value is a number before the assignment.
Undefined is the default value for uninitialized variablesWhenever we declare a variable without initializing it with a value, TypeScript initializes it as undefined . But TypeScript never assigns null to any variable. We have to assign Null to variable to make it null.
Note − There is no integer type in TypeScript and JavaScript.
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 ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With