I'm currently refactoring a service of mine and came across a rather annoying issue. I have an API which returns a object with multiple optional Properties. When I want to work with the Properties I first have to check weither this property is undefined or not, otherwise I will get an error. This can be done with an if-statement. After my refactoring i thought about putting the check inside the filter operator. This should work and only get me objects with the needed properties but now the linter still throws an error.
interface OptionalObject {
values?: number[]
}
const obs$$ = new BehaviorSubject<OptionalObject>({});
obs$$.pipe(
filter((val) => !!val.values),
map((val) => val.values.length) // Object is possibly 'undefined'
).subscribe(() => {
});
I think my Project uses ESLint
I tried it with a if and it worked but I want it to work with the filter of Rxjs
the solution is to use a TypeScript TypeGuard:
interface OptionalObject {
values?: number[];
}
const obs$$ = new BehaviorSubject<OptionalObject>({});
obs$$
.pipe(
filter((val): val is {values: number[]} => !!val.values),
map((val) => val.values.length)
)
.subscribe(() => {});