Improve Readability with TypeScript Numeric Separators when working with Large Numbers

Rares Matei
InstructorRares Matei

Share this video with your friends

Send Tweet
Published 4 years ago
Updated 4 years ago

When looking at large numbers in code (such as 1800000) it’s oftentimes difficult for the human eye to quickly see how big the number actually is. TypeScript allows us to use numeric separators to write numbers in a more human readable format (such as 1_800_000), while keeping the generated JavaScript unchanged.

Instructor: [00:01] If we had a really large number such as the population of Africa, it would be really hard to tell, at a glance, just how big this number actually is. It would involve a bit of a mental effort.

[00:12] Outside of programming, we usually use the comma separators to make it easier for other humans to read such large numbers. In our case, if we add commas on every third position, we can now instantly tell that it's approximately 1.2 billion.

[00:28] Since TypeScript 2.7, we can now add underscores as numeric separators to the numbers in our code. We'll assign the same number to this constant, but this time I'll add underscores in every third position. This not only makes the code more readable, but it also doesn't affect the final output at all. If we look at the result in JavaScript, we can see that all the underscores got compiled away.

[00:52] TypeScript also doesn't force you to use this feature in a specific way. You can add an underscore after each number, and you can even add them after the decimal point. Compilation won't fail, but it might make the code less readable, so it's up to the developer to use this feature responsibly.

[01:12] For a more real-life example, I'm now going to write an amount input class. I'll create a private static at the top to indicate the maximum amount it supports and amount field of type number to store the actual entered amount.

[01:28] I'll also create a show tooltip method that creates a tooltip and then hides it after a few milliseconds. Finally, I'll add a format million method that takes the current amount and returns the formatted string in millions.

[01:43] Even though we've added just a few underscores to the numbers in this class, because we're working with such large numbers, we've made the overall reading experience a bit more pleasant and the overall cognitive load of someone going through this much lower.

Denis Spiridonov
Denis Spiridonov
~ 3 years ago

It is not possible to specify the accessibility of statics—they are effectively always public. (from spec) In other words, private in private static MAX_ALLOWED is not possible.

~ 8 months ago

This particular behavior also works in plain JS, doesn't it?