Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Typescript accept a number value as a type?

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?

like image 303
user2987663 Avatar asked Nov 02 '17 13:11

user2987663


People also ask

What type of value is number in TypeScript?

The numbers in typescript are used as both integers as well as floating-point values.

Is integer a type in TypeScript?

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

Is number an object in TypeScript?

TypeScript like JavaScript supports numeric values as Number objects.

What is the difference between number and number in TypeScript?

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


2 Answers

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.

like image 192
Fenton Avatar answered Oct 20 '22 06:10

Fenton


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.

like image 23
Osman Cea Avatar answered Oct 20 '22 05:10

Osman Cea