Take a look at this scenario where the variable a
can potentially be null
, and is explicitly defined as such. Even when strict null checks are enabled, TypeScript does not flag a possible issue in this situation -
let a: string | null = "hello"
function b() {
a = null
}
b()
a.replace('2', '3')
Explore the code on the Typescript Playground.
If the same snippet was written in Flow, an immediate error would have been raised since the replace
method cannot be used with a null
type.
What steps can be taken to ensure type-safety in similar scenarios?