All you need to know about TypeScript’s CORE Types.
When TypeScript first came, it truly revolutionized how we have been writing JavaScript codes.
For the people who are not very much familiar with the whole TypeScript thing, here’s a run-down on what it is all about in a nutshell (otherwise skip it) :
- A JavaScript Superset.
- A language built on top of JavaScript.
- It adds new Features and Advantages to the JS ecosystem such as “Types”
What it is not :
- A “new” language.
- JavaScript’s competitor.
- TS cannot be executed by Browsers, as it is compiled down to JS in order for the browser to understands it first. Hence it is not a “Browser-language” such as JS.
So what are “Types” then?
Well, Types is one of the most basic concepts of Typescript and easier to understand.
Let’s say we have a Scenario in JS such as:
Which is pretty much expected right? But what if we drop in 2 and 3 as strings (such as add("2","3")
) and not numbers?
Errors?
Nope! There won’t be any errors but JavaScript would simply concatenate the strings and our output would be 23
The point is, we are prone to mistakes like that and JavaScript won’t be able to figure it out resulting in unexpected errors, hard to catch!
So, here Typescript’s “type system” comes into the picture which makes sure and we can only provide a certain data type (like only numbers and no strings).
In total, we have around 7 kinds of CORE TYPES available in Typescript ecosystem as of now, we will go through each one of them one by one:
- NUMBER: Like in our previous “error-prone code” we can explicitly tell to Typescript that we want our inputs to be only and only numbers and not some strings using a change of syntax in a TS file. Such as :
2. STRINGS: Similar to numbers, we have a “type” for strings too, in case we want to pass only strings and not numbers. such as :
3. BOOLEAN: We can assign a boolean type as well to make sure we are passing only boolean values and not some other data type.
4. OBJECTS: Type system isn’t limited to numbers and strings but it can handle complex structures as well such as objects.
Let’ say we have a very simple object in JS such as :
but, we want to make sure the name should always be a string and the age should always be a number, so we can write this code in TS using type-system for Objects, such as:
Notice in the above-mentioned code, how TS is making sure the name and age should only be a specific data type by assigning, then later we have created the object. Now for instance, if we try to assign a string to age instead of a number, it would throw an error.
5. ARRAY: Moving towards complex type systems, now we have an Array, where we can use types pretty easily.
Let’s say we want to make sure our variable Activities should always be an array no matter what, then we can assign it to a type of array as shown:
So, That sums up all about the CORE Types in TypeScript.
For any questions/suggestions reach out to me.
cheers xx.