DEV Community

Cover image for Number in Typescript - simple explanation with examples
Arika O
Arika O

Posted on • Updated on

Number in Typescript - simple explanation with examples

Specifying types is always a good idea since the value of a variable can change (intentionally or not) and sometimes it changes to something completely different and the code breaks. We can start with a variable called let year = 1997 and 50 lines of code later we mistakenly assign a Coco Jambo lyric to it and our variable will look like let year = "Ayyayaya coco jambo ayyayai". This could be funny or tragic, depending on where in our software this happens. Javascript can't help us avoid this kind of errors (since technically nothing wrong happens) but Typescript, with its beautiful types (some of them simple, some more complicated) can. So let's dive into types and start with number.

Number
Is one of the basic types. Just like in JS, in TS all numbers are floating point values. Syntactically, the way we specify types is by placing a colon after the name of the variable (or after the things we want to define types for), just before the equal sign, and write the data type we want that variable to hold. Like so:

let age: number = 35;
let salary: number = 2300;
Enter fullscreen mode Exit fullscreen mode

We just told Typescript that we want two variables, one called age and the other salary to store two numbers. So what, you could ask? How does that help us? I'm using the TS playground to show you what will happen if I'm trying to pass a string to the salary variable, which should only store numbers.

Alt Text

We get an error, underlined in red. Pretty neat, right? The editor complains and we can spot the mistake and correct it without needing to run the code.

One simple example where this is useful is inside a function that takes numbers as inputs but somehow we feed it strings by mistake:

Alt Text

Try to find out your profit using numbers, and you get a nice a final amount; try to extract a peanut and you get an error (plus a possible allergy).

Stay tuned for the next article in which I'll discuss the string type.

*Image source: Annie Spratt/ @anniespratt on Unsplash *

Top comments (0)