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

后端 未结 3 1691
太阳男子
太阳男子 2020-11-29 03:20

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

On my IDE (JetBrains WebStorm) the type

相关标签:
3条回答
  • 2020-11-29 03:37

    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;
    
    0 讨论(0)
  • 2020-11-29 03:48

    As the TypeScript doc says:

    var Number: NumberConstructor
    (value?: any) => number
    

    An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers.

    As it says, take any as parameter and return number or null

    It give an easy way to check a value is number or not

    Number("1234");   // 1234
    Number("1234.54") // 1234.54
    Number("-1234.54") // -1234.54
    Number("1234.54.33") // null
    Number("any-non-numeric") // null
    

    So simply we can use to check the number, like:

    if(Number(val)){
       console.log('val is a number');
    } else {
       console.log('Not a number');
    }
    
    0 讨论(0)
  • 2020-11-29 03:50

    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.

    0 讨论(0)
提交回复
热议问题