I have stumbled upon a situation and I am seeking feedback.
Given the following code,
import { Subject } from "rxjs";
import { first, map } from "rxjs/operators";
type Something = {
prop: number;
};
const source = new Subject<Something | undefined>();
source.asObservable().pipe(
first((value) => !!value),
map((value) => {
console.log(value.prop);
})
);
The type of the value on the map operator is still Something | undefiend, but we are sure we won't get any undefined since we are filtering by truthiness.
What's the best approach to handle this scenario, without having to check for truthiness of the value inside the map operator?
Dependencies:
[email protected]
[email protected]
tsconfig
strict: true
CodePudding user response:
You will need a type guard for that:
import { Subject } from "rxjs";
import { filter, first, map } from "rxjs/operators";
type Something = {
prop: number;
};
const source = new Subject<Something | undefined>();
function isDefined<T>(arg: T | null | undefined): arg is T {
return arg !== null && arg !== undefined;
}
source.asObservable().pipe(
first(isDefined),
map((value) => {
console.log(value.prop);
})
);
