【问题标题】:RxJS - fix type of combineLatest resultRxJS - 修复 combineLatest 结果的类型
【发布时间】:2022-01-16 07:51:30
【问题描述】:

当我使用combineLatest 组合两个发出可选值的可观察对象时,我经常在 Angular 中遇到这种情况。

基本模式是这样的:

const ob1: Observable<Transaction[] | null>;
const ob2: Observable<Price[] | null>;

const currentValue = combineLatest([ob1, ob2]).pipe(
  filter(([a, b]) => !!a && !!b),
  map(([a, b]) => {
    // Here the type of both and a and b is nullable
    const x = a.map(a => a.id); // This gives compilation error that a can be null
  });

我想在map 函数中工作,以便在两个可观察对象发出非空值时合并事件。

filter 确实会过滤,但每个元素的类型仍然是 T | null

我希望a 的类型为Transaction[]b 的类型为Price[],而不使用a!b!

这种模式在我的代码中重复了很多次,我想找到一个简短而优雅的解决方案,并且不需要我为每个用例编写样板代码。

我找到了一些答案how to fix this for a single value。但是如何为元组或数组执行此操作?

【问题讨论】:

    标签: angular typescript rxjs


    【解决方案1】:

    创建两种类型的所需元组将帮助您解决问题。

            function filterNullish<T, K>(): UnaryFunction<Observable<[T |null, K | null]>, Observable<[T, K]>> {
              return pipe(
                 filter(([a, b]: [T |null, K | null]) => !!a && !!b) as 
                 OperatorFunction<[T |null, K | null], [T, K]>
        );
    }
    
            const currentValue = combineLatest([ob1, ob2]).pipe(
                filterNullish() ,
                map(([a, b]) => {
                    const x = a.map(a => a);
                    const y = b;
                    return x;
                })).subscribe((r) => console.log(r));
    

    【讨论】:

    • 问题是 - 如何从V 中自动创建R(使用映射类型或类似类型),而不必为每个用例手动创建它。
    • 答案已更新。希望对您有所帮助。
    • 这是我所做的,但当然它只适用于具有 2 个元素的元组。我正在为任意数量的元素寻找通用解决方案。
    【解决方案2】:

    简单的铸造怎么样?在filter 之后添加另一个map 到管道:map(([a,b])=&gt; [a,b] as [Transaction[], Price[]]), 甚至将其投射到您的map 体内。

    【讨论】:

    • 这可行,但由于我经常使用这种模式,所以我正在寻找不那么冗长的东西。类似于this,但适用于数组。
    猜你喜欢
    • 2021-03-06
    • 2017-06-25
    • 2021-04-28
    • 2021-02-21
    • 2019-01-08
    • 1970-01-01
    • 2019-10-08
    • 1970-01-01
    • 2023-03-24
    相关资源
    最近更新 更多