TypeScript严格null检查数组中对象的字段

Sta*_*tav 0 typescript

在TypeScript中,尽管在对象数组中的可空字段上检查为null(strictNullCheck设置为true),编译器仍然抱怨"对象可能未定义".考虑以下:

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'
Run Code Online (Sandbox Code Playgroud)

链接到TS PlayGround(设置为strictNullCheck开)

但是,如果我们有:

const a : IA = {d: new Date()};
console.error(a.d == null ? "" : a.d.toString());
Run Code Online (Sandbox Code Playgroud)

然后编译器很高兴.

为什么这是理想的行为?如果我不想关闭strictNullCheck,那么这里的正确做法是什么?

Rya*_*ugh 5

TypeScript不会按索引跟踪数组元素; 换句话说,类型系统中没有机制可以识别两个表达式arr[0]必然指向同一个对象.

通常,这是一个很好的假设,因为保证数组元素的排序在同一元素的任何两个观察之间保持相同.我们可以从检查中看出,例如你没有sort在这两个访问之间调用,但在任何其他情况下,两个表达式不是一个接一个地进行评估,它不确定arr[0]两次都指向同一个对象.