How do you specify that a class property is an integer?

后端 未结 8 1173
旧巷少年郎
旧巷少年郎 2020-12-15 02:20

I\'m experimenting with TypeScript, and in the process of creating a class with an ID field that should be an integer, I have gotten a

相关标签:
8条回答
  • 2020-12-15 02:54

    Well, as you have seen, typescript haven't float data type such as javascript language. Only have the number that cover all int and double at same time; maybe you must make a function that take a number and check it if it's a int or double, by returning some state in case error/success. Something like this as method of your class:

    function SetN(x:number) {
       var is_int = parseInt(x) === parseFloat(x);
       if(is_int) this.n = x;
       return is_int;
    }
    
    //..
    y = 10.5;
    if(SetN(y)) {
      //OK
    } else {
       //error not set y isn't a int
    }
    

    Note: it doest not works for 10.0 e.g. If you want no really it, maybe you must conver it to string and try to find a ..

    0 讨论(0)
  • 2020-12-15 03:01

    int was reserved for future use keyword in earlier versions of javascript (ECMAScript if you prefer). But it is a valid word now (where "now" equates to "in the latest spec").

    For instance, in 262 it was still reserved, http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf

    It would make nice addition to typescript to have an int datatype implemented but with all compile-time type checking and casting rules available.

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