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.