【发布时间】:2018-04-21 22:13:13
【问题描述】:
在 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'
Link 到 TS PlayGround(设置 strictNullCheck 开启)
但是,如果我们有:
const a : IA = {d: new Date()};
console.error(a.d == null ? "" : a.d.toString());
那么编译器就开心了。
为什么这是期望的行为?如果我不想关闭strictNullCheck,那么正确的做法是什么?
【问题讨论】:
标签: typescript