I have a code example below and at line const cars = x.cars.filter() i am getting an error object is possibly undefined for x.cars. To overcome this issue i have added an if check like if(x.cars). By adding this i have issue with code coverage karma unit testing for this code. So i researched and found there is an Null assertion operator to overcome this typescript compiler issue. Is it ok to use Null assertion operator in this scenario or is there anything else i need to take into consideration ?
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;
});
Planning to use Null Assertion Operator as below
const cars = x.cars!
.filter(x => x.selected)
.map(x => x.name)
.join(',');
return `${x.name}~${cars}`;