TypeScript 2.7: Numeric Separators
TypeScript 2.7 brought support for numeric separators as outlined in the Numeric Separators ECMAScript proposal. Within a numeric literal, you can now group digits by putting an underscore as a separator character between them:
const worldPopulationIn2017 = 7_600_000_000;
const leastSignificantByteMask = 0b1111_1111;
const papayawhipColorHexCode = 0xFF_EF_D5;
The separators don't change the value of a numeric literal, but the logical grouping makes it easier for humans to read the number at a glance. Check out Axel Rauschmayer's post ES Proposal: Numeric Separators for more details and some restrictions of numeric separators.
Downleveling Numeric Literals with Separators
TypeScript will emit the following JavaScript code when we compile the above code with target set to es2015:
const worldPopulationIn2017 = 7600000000;
const leastSignificantByteMask = 255;
const papayawhipColorHexCode = 16773077;
At the time of writing, TypeScript never emits the separator characters, no matter which language level we're targeting (including --target esnext). Also, if you're using a numeric separator, the numeric literal will be emitted in decimal form, even if the target ECMAScript version supports binary, octal, or hexadecimal literals (as ES2015 does, for example).
However, the TypeScript team is considering emitting numeric literals as they are (to the degree supported by --target), so in the future, the generated JavaScript code might look closer to the original TypeScript code.
This post is part of the TypeScript Evolution series:
- TypeScript 2.0: Non-Nullable Types
- TypeScript 2.0: Control Flow Based Type Analysis
- TypeScript 2.0: Acquiring Type Declaration Files
- TypeScript 2.0: Read-Only Properties
- TypeScript 2.0: Tagged Union Types
- TypeScript 2.0: More Literal Types
- TypeScript 2.0: The never Type
- TypeScript 2.0: Built-In Type Declarations
- TypeScript 2.1: async/await for ES3/ES5
- TypeScript 2.1: External Helpers Library
- TypeScript 2.1: Object Rest and Spread
- TypeScript 2.1: keyof and Lookup Types
- TypeScript 2.1: Mapped Types
- TypeScript 2.1: Improved Inference for Literal Types
- TypeScript 2.1: Literal Type Widening
- TypeScript 2.1: Untyped Imports
- TypeScript 2.2: The object Type
- TypeScript 2.2: Dotted Properties and String Index Signatures
- TypeScript 2.2: Null-Checking for Expression Operands
- TypeScript 2.2: Mixin Classes
- TypeScript 2.3: Generic Parameter Defaults
- TypeScript 2.3: The --strict Compiler Option
- TypeScript 2.3: Type-Checking JavaScript Files with --checkJs
- TypeScript 2.3: Downlevel Iteration for ES3/ES5
- TypeScript 2.4: String Enums
- TypeScript 2.4: Weak Type Detection
- TypeScript 2.4: Spelling Correction
- TypeScript 2.4: Dynamic import() Expressions
- TypeScript 2.5: Optional catch Binding
- TypeScript 2.6: JSX Fragment Syntax
- TypeScript 2.7: Numeric Separators
- TypeScript 2.7: Strict Property Initialization
- TypeScript 2.8: Per-File JSX Factories