0

I have a Typescript project, and I've found that when I access a property or function of a property that is optional, it doesn't error.

For example:

type Example = {
    bar?: string[]
}

const foo: Example = {}

// No error, but the code will crash!
foo.bar.map(string => string.toUpperCase())

bar is an optional property, so foo being an empty object is completely valid. But Typescript doesn't complain that foo.bar might be undefined, and therefore .map() will result in Cannot read properties of undefined.

Is this something I can do with a eslint rule, or a compiler option? I want it to flag up the issue and require something like foo.bar?.map(), which would not fail.

cogm
  • 275
  • 6
  • 17
  • 1
    go to tsconfig.json and set `strictNullChecks` to `true` or even better: set `strict` to `true` – Tobias S. Jul 05 '22 at 20:43
  • @TobiasS. Ah, doh I'd disabled strict earlier to test a different thing. Perfect, thank you. – cogm Jul 05 '22 at 20:45

1 Answers1

0

Solved in comments: strict: true in tsconfig

dippas
  • 58,591
  • 15
  • 114
  • 126
cogm
  • 275
  • 6
  • 17
  • @dippas: Why do you say that? This looks like an answer to me. It's elevating a suggested answer from the comments to the answers section, where it belongs. – Jeremy Caney Jul 05 '22 at 23:40