Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript primitive types: any difference between the types "number" and "Number" (is TSC case-insensitive)?

Tags:

typescript

tsc

People also ask

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

What are the primitive types in TypeScript?

TypeScript supports 7 primitive types number , string , boolean , bigint , symbol , undefined , and null . All other data types are objects in Typescript.


To augment Ryan's answer with guidance from the TypeScript Do's and Don'ts:

Don't ever use the types Number, String, Boolean, Symbol, or Object These types refer to non-primitive boxed objects that are almost never used appropriately in JavaScript code.

/* WRONG */
function reverse(s: String): String;

Do use the types number, string, boolean, and symbol.

/* OK */
function reverse(s: string): string;

JavaScript has the notion of primitive types (number, string, etc) and object types (Number, String, etc, which are manifest at runtime). TypeScript types number and Number refer to them, respectively. JavaScript will usually coerce an object type to its primitive equivalent, or vice versa:

var x = new Number(34);
> undefined
x
> Number {}
x + 1
> 35

The TypeScript type system rules deal with this (spec section 3.7) like this:

For purposes of determining subtype, supertype, and assignment compatibility relationships, the Number, Boolean, and String primitive types are treated as object types with the same properties as the ‘Number’, ‘Boolean’, and ‘String’ interfaces respectively.