I had a bug in my Angular 4 project where I had declared a variable:
debounce: 300;
instead of
debounce = 300;
So of course this.debounce
was undefined before the fix.
Shouldn't Typescript give me an error in this case?
The numbers in typescript are used as both integers as well as floating-point values.
Note − There is no integer type in TypeScript and JavaScript.
TypeScript like JavaScript supports numeric values as Number objects.
number Vs Number The primitive data type does not have properties or methods. The Number is a wrapper object around number . It is created by using the syntax new Number(value) .
If you declare a variable with a type annotation of 300
, that means not only is the type numeric, but only the value 300
is acceptable:
var debounce: 300;
You will get an error if you attempt to assign, say, 200:
debounce = 200;
Switch on strict null checks, and the compiler will catch this kind of problem (you meant to assign the 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 the variable, strict null checks points out you never assigned a value - thus telling you that you made an annotation, not an assignment.
You can basically pass (almost) anything as a value type to Typescript. So if you say:
class SomeClass {
debounce: 300 | 500 | 700;
constructor() {
this.debounce = 400;
}
}
You will get a type error, since typescript is expecting the value for debounce to be 300
, 500
or 700
, not just any number. This means that you can be more specific about type annotations.
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