At my workplace, we rely on Typescript's strict null checking feature to help us catch exceptions caused by null or undefined variables. Despite this, a recent bug has emerged that seems to slip past Typescript's detection. The following code snippet illustrates the issue:
interface IMyObj {
foo: string;
}
const myArr: IMyObj[] = [];
const myObjProp = myArr[0].foo;
console.log(myObjProp);
While Typescript compiles this code without any errors, running it will result in a clear type error message:
Uncaught TypeError: Cannot read property 'foo' of undefined
One solution could be to define all array types as (IMyObj | undefined)[]
instead of just IMyObj[]
, but this approach is prone to human error as it is easy to miss making such changes throughout the codebase.
Is there a way for Typescript to detect potential undefined references like myArr[0]
?