Object is possibly undefined VS Null Assertion Operator => 正确的使用方法是什么?
Object is possibly undefined VS Null Assertion Operator => What is the correct way to use?
我在下面和第 const cars = x.cars.filter() 行有一个代码示例,我收到一个错误 object is possibly undefined 对于 x.cars。为了克服这个问题,我添加了一个 if 检查,如 if(x.cars)。通过添加此代码,我对该代码的代码覆盖业力单元测试有疑问。所以我研究并发现有一个 Null 断言运算符来克服这个打字稿编译器问题。在这种情况下可以使用 Null 断言运算符吗?还有什么我需要考虑的吗?
this.carOptions$().pipe(
map((result: any): string => {
return result
.filter(x => x.selected)
.map(x => {
if (x.cars) { //added this condition to overcome object is possibly undefined error
const cars = x.cars
.filter(x => x.selected)
.map(x => x.name)
.join(',');
return `${x.name}~${cars}`;
}
})
})
).subscribe(result => {
this.result = result;
});
计划如下使用空断言运算符
const cars = x.cars!
.filter(x => x.selected)
.map(x => x.name)
.join(',');
return `${x.name}~${cars}`;
使用 !.
运算符后测试代码覆盖率得到改善 是谎言。
我认为这不是好的做法。它可能有用。它可能适合您的情况(如果您以某种方式完全确定基础对象永远不会 null
),但请不要将其视为灵丹妙药。
为什么这不是一个好习惯?因为如果对象是 null
/undefined
,您的代码将以与您不使用此运算符完全相同的方式中断。但是编译器就是无法抱怨,你的测试覆盖工具分析器也是如此。
相关问答:
从某种意义上说,您的代码使用 null 断言运算符会更简单一些。您跳过了 if
。但是如果 cars.x
是 null
,带有 if
的代码不会抛出错误,而另一个会抛出错误。请注意这一点。
我在下面和第 const cars = x.cars.filter() 行有一个代码示例,我收到一个错误 object is possibly undefined 对于 x.cars。为了克服这个问题,我添加了一个 if 检查,如 if(x.cars)。通过添加此代码,我对该代码的代码覆盖业力单元测试有疑问。所以我研究并发现有一个 Null 断言运算符来克服这个打字稿编译器问题。在这种情况下可以使用 Null 断言运算符吗?还有什么我需要考虑的吗?
this.carOptions$().pipe(
map((result: any): string => {
return result
.filter(x => x.selected)
.map(x => {
if (x.cars) { //added this condition to overcome object is possibly undefined error
const cars = x.cars
.filter(x => x.selected)
.map(x => x.name)
.join(',');
return `${x.name}~${cars}`;
}
})
})
).subscribe(result => {
this.result = result;
});
计划如下使用空断言运算符
const cars = x.cars!
.filter(x => x.selected)
.map(x => x.name)
.join(',');
return `${x.name}~${cars}`;
使用 !.
运算符后测试代码覆盖率得到改善 是谎言。
我认为这不是好的做法。它可能有用。它可能适合您的情况(如果您以某种方式完全确定基础对象永远不会 null
),但请不要将其视为灵丹妙药。
为什么这不是一个好习惯?因为如果对象是 null
/undefined
,您的代码将以与您不使用此运算符完全相同的方式中断。但是编译器就是无法抱怨,你的测试覆盖工具分析器也是如此。
相关问答:
从某种意义上说,您的代码使用 null 断言运算符会更简单一些。您跳过了 if
。但是如果 cars.x
是 null
,带有 if
的代码不会抛出错误,而另一个会抛出错误。请注意这一点。