Understanding the Non-null Assertion Operator '!'
So what is the !
in TypeScript?
This is actually known as a non-null assertion operator.
Take for example the following code:
The following will return a type Item | undefined
. In some scenarios, we are not allowed to parse an undefined
value and therefore we need to write extra code just to handle the undefined
value first.
One of the most common way is to do the following.
Or we could type cast it back to the Item type like the following.
However, with the !
in TypeScript. We are able to just do the following and return the type Item
quickly.
The use of !
however does not remove the fact that the Array.find()
will not return a null
or undefined
at all.
Swift
Swift is used as the programming language for creating apps on iOS, macOS, watchOS.
Since I have created an Augmented Reality(AR) App in Swift before, the !
works very similarly and is very commonly used.
The !
in Swift is used to force unwrapping of optionals.
Example:
So as you have guessed it, the !
actually forces the optional value in the variable name
and gain access to the String
value.
Summary
And that is all for this post. Just wanted to share something regarding the !
operator that I discovered while writing code in Swift and now being able to also use it in TypeScript.