Strictly speaking, using filter alone to remove undefined values doesn't do everything that you need. It filters out the undefined values, but does not change the type to indicate that undefined is no longer a possible value.
In the example:
const obs = new Subject<string | undefined>;
const stringObs = obs.pipe(filter(x => x !== undefined))
the stringObs observable still has the type Observable<string | undefined>.
To get round this problem, you need to use:
const stringObs = obs.pipe(filter(x => x !== undefined) as OperatorFunction<string | undefined, string>)
This is only really an issue if you use strict null checks, but if you do (and arguably you should) then creating a custom operator suddenly makes a lot more sense! Something like
function filterNullish<T>(): UnaryFunction<Observable<T | null | undefined>, Observable<T>> {
return pipe(
filter(x => x != null) as OperatorFunction<T | null | undefined, T>
);
}
does the job.
You can then use:
const stringObs = obs.pipe(filterNullish())
and the type of stringObs will be Observable<string>. I was quite impressed that Typescript manages to infer the type of T correctly.
filter(Boolean)even though this will filter out also allfalse,''and so on.