Type assertions are not a substitute for non-null assertions

submited by
Style Pass
2024-11-16 11:00:06

Take JavaScript’s Map data structure — its get and has methods are defined like so in TypeScript:

get‘s return type of V | undefined can result in frustration when you know that the return value is not undefined — like when you’ve already checked for the key’s presence via has:

An easy fix for the error above is to assert that the return value is of type number via a type assertion:

Leave a Comment