HiveBrain v1.2.0
Get Started
← Back to all entries
gotchatypescriptMajor

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
typescriptanyandbetweenthedifferenceprimitivecaseinsensitivenumber

Problem

I meant to write a parameter of type number, but I misspelled the type, writing Number instead.

On my IDE (JetBrains WebStorm) the type Number is written with the same color that is used for the primitive type number, while if I write a name of a class (known or unknown) it uses a different color, so I guess that somehow it recognizes the misspelled type as a correct/almost-correct/sort-of-correct type.

When I compile the code, instead of complaining for example that the compiler couldn't found a class named Number, TSC writes this error message:

Illegal property access


Does that mean that number and Number both co-exists as different types?

If this is true, which is the difference between those classes?

If this is not the case, then why it simply didn't write the same error message it displays for unknown classes ("The name 'Number' does not exist in the current scope")

This is the code:

class Test
{
    private myArray:string[] = ["Jack", "Jill", "John", "Joe", "Jeff"];

    // THIS WORKS
    public getValue(index:number):string
    {
        return this.myArray[index];
    }

    // THIS DOESN'T WORK: ILLEGAL PROPERTY ACCESS
    public getAnotherValue(index:Number):string
    {
        return this.myArray[index]; 
    }
}

Solution

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.

Code Snippets

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

Context

Stack Overflow Q#15487220, score: 79

Revisions (0)

No revisions yet.