Typescript Bang
The "non-null assertion operator" or "!" at the end of an operand is one way to tell the compiler you're sure the thing is not null, nor undefined. In some situations, the compiler can't determine things humans can.
For example, say we have a treasure map with some gold in it.
type TreasureMap = Map<string, number>
const map: TreasureMap = new Map()
const treasure = 'gold'
map.set(treasure, 10)
And we're cranking out some code that tells us if
function isItWorthIt(map: TreasureMap) {
return map.has(treasure) && map.get(treasure) > 9
}
Obviously we are checking if the map has gold first. If it doesn't, the execution returns early with false. If it does, then we know we can safely access the value.
But the compiler gets really upset about this:
Object is possibly 'undefined'. ts(2532)
In this case, the compiler doesn't keep map.has(treasure)
in context when evaluating map.get(treasure)
. There is more than one way to solve this, but for now we can simply "assert" our superiority over the compiler with a bang.
return map.has(treasure) && map.get(treasure)! > 9
Typscript Docs - non-null-assertion-operator
Tweet