TypeScript tricks that make developers life easier! — Part 2
This is part 2 of my article on “TypeScript tricks that make developers life easier”. If you are interested to learn more typescript tricks, please also read my previous article.
In this article, we will look at 4 useful typescript tricks that can help you to write better TypeScript!
1) Template literals for dynamically typed strings
Have you ever wondered what is the problem with accepting defined values as string parameters?
In the example below, lets assume that we will be accepting values that will always end with “Event”.
In this case, we are not enforcing the variable eventType. This let us to pass invalid values without errors.
In order to enforce that we will be accepting values that will end with “Event”, we can change the type of parameter as below.
Now you can clearly see that we get error for the invalid arguments passed.
2) Build key value pair type using Record Type
It is quite common to have key value pairs while coding. Here is a very simple example
The same can be re-written as
Looks nice. But what difference it makes compared to the previous syntax.
Actually nothing. But we can be more expressive using this syntax. Let’s say we want to restrict the keys to be more specific.
In our example, lets assume we want only light colors in our color code mapper. Then we can express that like below.
3) Use constructor assignment to create properties in a class
The value passed via constructor in a class cannot be accessed directly via class object. In the below example, as you can see, we have to assign the name to another class property in order to access it.
There is a better way to do this property assignment. Instead of introducing additional properties in the class and assigning values in the constructor, we can directly add the access modifier to the constructor argument.
4) Type guards + unknown type to avoid errors
Imagine we have a function like below which acts on the input parameter in different ways.
These type of functions are very error prone. First, they do not warn us at compile time. And when we invoke the function with a number, the example here will throw the error as toUpperCase() and print() do not exist in number type.
To enforce type guard, we can change the argument type to unknown. Lets see what happens when we do this.
We can clearly see that unknown type cautioning us about possible errors. This means we have to specify the type guard before using the value. And it can be done like below.
As you can see from the example above. This function is less error prone!
With this, we will wrap up this series. I hope that all the tips you have learned in this series will be useful to you in your projects!
Note: You can find all the code snippets used in this article here.