7 Useful TypeScript Operators and Keywords
Introduction
This guide will present to you the following Typescript’s operators and keywords that are too often forgotten : !!
, is
, in
, as
, ?.
and ??
.
Bang bang it shot me down
Everyone known the logical operator!
which perform a logical negation on the provided operand.
Few people knows of it’s big brother, the !!
operator that ultimately cast the given operand to a boolean value.
> Examples :
The “bang bang” operator is useful to perform nullable checks in a sleek way.
> Example with and without the bang bang operator :
Wait a minute, who are you again ?
The is
keyword is used to perform type predication. Which consist to dynamically tell Typescript about the type of a variable.
In the following example, we want to display the size of the tank where Fish
are living into. The thing is, we have an array containing different kind of Animal
:
In the example, due to the call of isFish
Typescript will know that x
is a Fish
and will stop to show you errors.
> Example of code without type predication :
Are you in here ?
The operator in
checks if the given object contains the provided key. It is handy, but careful about where it is looking at, any non object values will make it crash.
> Example with obj
worthing null
:
You are an Apache helicopter now
In a perfect world, Typescript would be a genius capable of inferring the types of every functions and variables. In reality, Typescript is limited and it not able to infer the type of the variable in the way you would expect.
There goes your new ally, the as
keyword.
as
allows you to manually type any variable or function, overriding any infer that would have been made by Typescript.
> Syntax examples :
> Real case example :
In the above code, we are creating two Animal
, one Fish
and one Bird
. Then we store them both inside of an array — inferred by Typescript as (Fish | Bird)[]
.
At this moment, we know as a developer that the first element of the array is a Fish
, calling animals[0].swim()
should work. But unfortunately, Typescript does not agree.
Using as
here allow us to force Typescript to accept that animals[0]
is a Fish
.
Extra careful steps
The support of the Optional chaining feature has been added in Typescript 3.7.
The ?.
operator finally provide a sleek solution to undefined properties accesses.
We are all familiar with the error “cannot read property X of undefined” when trying to access an non existing key:
We are also all familiar with the solution :
It is long, it is repetitive, and it is ugly.
With ?.
now enjoy !
Backup plan
In addition to optional chaining, Typescript 3.7 also bring up the nullish coalescing which can be used to set up a default value.
> Example with a combo between optional chaining and nullish coalescing :
Thank you for reading this article. Let me know if something is wrong or if there are anything to add. This being my first article and as a non english speaker, I’m eager to improve !
Have a good day :)