I recently encountered an issue in my Typescript project where accessing properties or functions of optional properties did not throw any errors.
Here is an example:
type Example = {
bar?: string[]
}
const foo: Example = {}
// Although no error occurs, the code will crash!
foo.bar.map(string => string.toUpperCase())
In this case, bar
is an optional property, so having foo
as an empty object is valid. However, Typescript does not warn that foo.bar
could be undefined, leading to a .map()
call resulting in
Cannot read properties of undefined
.
Is there a way I can set up an eslint rule or compiler option to catch this issue and require something like foo.bar?.map()
to avoid failure?