When using TypeScript and checking for null on a nullable field inside an object array (where strictNullCheck
is set to true
), the compiler may still raise an error saying that 'Object is possibly undefined'. Here's an example:
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'
Try it on TS PlayGround (with strictNullCheck
enabled)
Strangely enough, if we write:
const a : IA = {d: new Date()};
console.error(a.d == null ? "" : a.d.toString());
then the compiler does not show any errors.
Why does this happen? And what would be the best approach in this scenario if we want to keep strictNullCheck
activated?