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
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;
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.
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:
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
*Image source: Annie Spratt/ @anniespratt on Unsplash *