Why does typescript accept a numeric value as a type?

I had an error in my Angular 4 project where I declared a variable:

debounce: 300; 

instead

 debounce = 300; 

So of course this.debounce was undefined before the fix.

Should typescript not report an error in this case?

+7
javascript angular typescript
source share
4 answers

If you declare a variable with an annotation of type 300 , this means that not only the type is numeric, but only the value 300 valid:

 var debounce: 300; 

You will receive an error message if you try to assign, say, 200:

 debounce = 200; 

Turn on strict zero checks, and the compiler will catch this problem (you should assign a value, not a type annotation):

 var debounce: 200; // Strict null checks tells you here that you have done something strange var x = debounce; 

In this case, when you try to use this variable, strict zero checks indicate that you never assigned a value, so you are told that you made the annotation, not the task.

+17
source share

Basically, you can pass (almost) something as a type of a Typescript value. Therefore, if you say:

 class SomeClass { debounce: 300 | 500 | 700; constructor() { this.debounce = 400; } } 

You will get a type error, because typescript expects the value for debounce to be 300 , 500 or 700 , not just any number. This means that you can be more specific for type annotations.

+9
source share

This line is correct because you inadvertently used literal-types ( for more information ):

This example will help you understand how literal-types are used to limit variables to a finite set of possible values :

 let zeroOrOne: 0 | 1; zeroOrOne = 0; // OK zeroOrOne = 1; // OK zeroOrOne = 2; // Error: Type '2' is not assignable to type '0 | 1' 
+1
source share

This is not a permanent ad. You thought you declared a variable and assigned a value implicitly printed. You are not right. This is a declaration of type number that accepts only certain values.

 debounce: 300; 

and then assign it

 this.debounce = 300; 

Typescript will not give you an error because it is syntactically corrected, but run-time errors should be used for undefined variables.

0
source share

All Articles