When it comes to TypeScript, there are three features I wanted to share with you that I found pretty cool.
For my examples, I used TypeScript Playground.
Conditional Types
Conditional types were something I found extremely cool, being able to conditionally return a type, I actually found it hard to learn due to misunderstanding the term extends
in this context.
Let's have a look at a simple example:
Here all we are saying is, if Dog
is of type object
, if it contains that, then we want the type NumberOrString
to be a number, otherwise, if that wouldn't be the case for some reason, then we want the type to be a string.
Here you can read more on conditional types.
Template Literal Types
Template Literal Types are just the pure definition of flexibility, I was actually astonished when I learned about them ๐.
Let's say we want to define some CSS values, and we want developers to only be able to pass px
or rem
values, then we can do something like this:
Here we have two correct variables and one which is false, the one TypeScript complains about. The variables with the type Value
must explicitly have a number and unit of either px
or rem
.
Here you can read more on template literal types.
Asserts
Let's say we have a simple function, arrayOfNumbers
, that returns an array of numbers with the given inputs, but the type of the inputs is unknown
.
Using asserts
of TypeScript we can create a function that we can invoke inside of arrayOfNumbers
, in order to ensure the inputs are of type number, that way TypeScript won't complain anymore.
Now the function arrayOfNumbers
doesn't complain, because using our assertIsNumber
function, we ensure the inputs of the function are of type number, otherwise, we throw an error if that is not the case.
We created a function which asserts that the inputs are of type number, but you can do the same with type string, boolean and other types ๐.
Here you can find more examples of assert functions.