In TypeScript, despite checking for null on a nullable field in an object array (with strictNullCheck set to true), the compiler still complains that the 'Object is possibly undefined'. Consider the following:
interface IA {
d?: Date
}
const arr : IA[] = [{d: new Date()}];
console.error(arr[0].d == null ? "" : arr[0].d.toString());
// ^ complains that "Object is possibly 'undefined'
Link to TS PlayGround (set strictNullCheck on)
However, if we have:
const a : IA = {d: new Date()};
console.error(a.d == null ? "" : a.d.toString());
then the compiler is happy.
Why is this the desired behavior? And what would be the correct practice here if I don't want to turn strictNullCheck off?