What is Typescript? Although is only seven years old, I'm sure most of us heard of it, especially now that more and more jobs are asking us to be at least familiar with it. Wikipedia says that:
Simply put, a
Before I'll go into details, we need to understand the difference between a static and a dynamic typed language.
A language is statically-typed if the type of a variable is known at compile-time instead of at runtime. Common examples of statically-typed languages include Java, C, C++, FORTRAN, Pascal and Scala. This is the case of Typescript also. Imagine that you could have a way to make it impossible for other developers to use your code in ways it wasn't planned to. Let's say, feed strings to a function named
number type will be treated as a
string type so the concatenation can take place.
This situation won't be possible in strong typed languages because they don't allow type coercion so they'll raise errors.
Ignore the syntax for now, as all you need to understand from the code is that we have a function that accepts two arguments of type number (this is what
:number means), returns a number (this is the
:number after the parenthesis) and that we are trying to pass a number and a string as parameters. Although the code doesn't look much different, it will already throw an error at compile time because we explicitly told Typescript that we want two numbers as arguments. To better understand this, I ran some code in a Typescript playground (you can find it here: https://www.typescriptlang.org/play/), and this was the result:
We can see that when trying to pass a string to the function, instead of a number, the string gets an underline in red. Upon inspecting the variable, we can see the following error:
So basically, Typescript doesn't allow us to use a string instead of a number and warns us about it. The code won't compile so the error will never get as far as runtime. What we see in action here is editor support which helps us spot common errors as we type the code (just like spell checkers warn us about grammar mistakes).
In my next text I will write about how we can use Typescript - hint: we need a transpiler - and the type of files we need to write our code in.
Image source: Oskar Yildiz/ @oskaryil on Unsplash