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

后端 未结 8 1177
旧巷少年郎
旧巷少年郎 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:48

    TypeScript is a superset of JavaScript, which doesn't have a concept of an int. It only has the concept of a number, which has a floating point.

    Philosophically, the amount of work the compiler would have to do to enforce only whole numbers for a TypeScript int type could potentially be massive and in some cases it would still not be possible to ensure at compile time that only whole numbers would be assigned, which is why it isn't possible to reliably add an int to TypeScript.

    When you initially get intelliSense in Visual Studio, it isn't possible for the tooling to determine what to supply, so you get everything, including int - but once you are dealing with something of a known type, you'll get sensible intelliSense.

    Examples

    var myInt: number;
    var myString: string;
    
    myInt. // toExponential, toFixed, toPrecision, toString
    myString. // charAt, charCodeAt, concat, indexOf, lastIndexOf, length and many more...
    

提交回复
热议问题