TypeScript Type features for cleaner code
Only specific values allowed in TypeScript
You can limit the values a variable can have using String Literal Types. Here is an example of how to use String Literal Types in TypeScript.
TypeScript will throw an error if the type doesn't match the expected. This feature can come in handy for error handling logic. For example, error code maps and their messages can be coordinated for more information rich handling.
Here is an example:
loginErrorMessages won't take a property other than those specified in the type
Here is an example for number type in TypeScript:
Here is an example of an array in TypeScript:
Template Literal Types in TypeScript
If you've ever worked with Tailwind color palettes, you'd experience the pain of maintaining combinations. Here is an example:
The above consists of 220 string literals. Imagine if we had to expand the color palette and support them all. This is where Template Literal Types comes in. This feature shipped in TypeScript
Here is an example:
This is much easier to visually digest and maintain.
Tuples in TypeScript
Here is an example of a tuple used in TypeScript:
coords can only be given values that are of
number type, and only 2 values. Here is another example where the data breaks the expected typing:
The main use of Tuples is in limiting the types, as well as the number of items it can take. Types don't have to be same, you can mix and match as needed to enforce the tuple.
Intersection types in TypeScript
In MySQL, you can split up related data into different tables. For example, instead of a single table containing all the fields:
We can split it up into multiple tables to contain specific sets of data.
Then we join all these together in the query when we need to mix and match our intersecting data. We can do something similar in TypeScript. Here is an example:
Using the 'Pick' helper in TypeScript
Pick helper type can help you 'pick' specific properties from an interface.
Let's take a look at the example below. We want to create a type with only
name, and these properties should match those in the original
User type. So we can write something like this:
However, TypeScript provides a helper type
Pick which filters properties based on only what you need.