Introduction to Typescript

Introduction to Typescript

What is typescript?

TypeScript is a superset of JavaScript which primarily provides optional static typing, classes, and interfaces.

You might be thinking why typescript?

Typescript is very powerful in terms of making the development process faster and also debugging and refactoring easier. HOW? Declaring types explicitly drastically decreases chances of errors and typescript inference helps by blocking off the unnecessary mistakes using discriminated unions. Let's dig deeper and understand more about the benefits and usage of typescript✏💯

What are types?

Types are basically data types (number, boolean, string, etc ), with which we specify the type of variables, function parameters, and object properties. We can specify the type using: Type. For example below , we are defining what properties the user object will contain, and the type of those properties.

type User = {
id : number ;
name : string ;
gender : | 'girl' | 'boy' 
hobbies : [string] ;
}

Now comes the power of defining the object user type. In the below image, you can see typescript throwing constant error that ' Type User is missing the following properties from type 'User': name, gender, hobbies'. Now you see, you don't have to remember 🧠 what properties an object will have and constantly go back and forth to check as typescript will do the work for you. It will be the first layer of defense 🗡 while writing more code and touching other code.

image.png

Easy documentation

Here, adding comments in the Type of user can be useful later as mini documentations. Adding new instances of objects will be also easier.

image.png

Discriminated Unions

In type user, we defined the gender of user gender: | 'girl' | 'boy' . This meant the key gender will only have only one of these two values. No the interesting part 🧩, if I added something else instead of the given options, typescript will throw an error. 😮

image.png

Some more power of discriminated union

In the image below, we have defined that an animal with type: 'bird' will have the ability: 'fly' and, with type: 'fish' will have the ability: 'swim'. Simple as that 👍

image.png

Now, while we write about a type: bird, only fly ability will be suggested. Similarly, when we describe type: ' amphibian', both 'swim ' and 'breath in water and on land ' is suggested.

image.png

image.png

Final Remarks

And these are just some small examples of the power of typescript and might seem that very tedious ⚒ work to type out every type. But when we work on a bigger codebase, with multiple files 🗃 , and a very large amount of data. Adopting Typescript comes in handy and is very beneficial in terms of easing the development 👩‍💻 process.

Have any thoughts 💭about this blog, comment below.

Connect with me on Twitter 📥

Happy Coding!!