1

Consider this example where a is possibly null, and is explicitly declared so. Even with strict null checks enabled, typescript does not warn me about a possible error here -

let a: string | null = "hello"

function b() {
  a = null
}

b()

a.replace('2', '3') 

Link to the Typescript Playground.

The same code written in flow would have immediately errored out as the replace method is not available for a null type.

What can I do ensure type-safety in such scenarios?

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Shubham Kanodia
  • 6,036
  • 3
  • 32
  • 46

1 Answers1

1

Since you are explicitly allowing null values, you need to consider handling this behavior manually. hence, you may use this

(a || '').replace('2', '3');
Derviş Kayımbaşıoğlu
  • 28,492
  • 4
  • 50
  • 72