Mastering TypeScript 3
上QQ阅读APP看书,第一时间看更新

Numeric separators

TypeScript also includes support for the ECMAScript standard to allow an underscore separator (_) when defining large numbers. Consider the following code:

let oneMillion = 1_000_000; 
console.log(`oneMillion = ${oneMillion}`); 

Here, we have defined a numeric variable named oneMillion with the value of 1 million. Note the use of the _ character to allow for a more human-readable representation of this large number. When TypeScript emits the equivalent JavaScript, it will convert this human readable number to a decimal equivalent, so the output of this code will be as follows:

oneMillion = 1000000; 

These numeric separators can also be used on other numbers, such as hexadecimal values, as follows:

let limeGreenColor = 0x00_FF_00; 
console.log(`limeGreenColor = ${limeGreenColor}`); 

Here, we have defined a numeric value called limeGreenColor, and assigned the hexadecimal value of 00FF00 to it. Note again, that the separators make this number more human readable, and that the emitted JavaScript will contain the decimal equivalent, which means the output of this code would be as follows:

limeGreenColor = 65280