Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript : Type 'number' is not assignable to type '0'

Tags:

typescript

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?

like image 688
ngShravil.py Avatar asked Aug 10 '19 11:08

ngShravil.py


People also ask

Is not assignable to type number in TypeScript?

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.

Is not assignable to type number []?

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.

Can TypeScript numbers be undefined?

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.

Does TypeScript have integer type?

Note − There is no integer type in TypeScript and JavaScript.


1 Answers

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 ;)

like image 176
Julian Avatar answered Sep 19 '22 03:09

Julian