7 Useful TypeScript Operators and Keywords
This guide will present to you the following Typescript’s operators and keywords that are too often forgotten :
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 ?
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
In the example, due to the call of
isFishTypescript will know that
x is a
Fish and will stop to show you errors.
> Example of code without type predication :
Are you in here ?
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
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 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
animals.swim() should work. But unfortunately, Typescript does not agree.
as here allow us to force Typescript to accept that
animals is a
Extra careful steps
The support of the Optional chaining feature has been added in Typescript 3.7.
?. 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.
?. now enjoy !
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 :)