【问题标题】:Why can't typescript infer tuple return type in RxJs stream?为什么打字稿不能推断 RxJs 流中的元组返回类型?
【发布时间】:2022-01-18 16:47:23
【问题描述】:

在组成一个可观察的流时,从映射函数返回一个元组被编译器推断为一个联合而不是一个元组。

例如:

import { Component } from '@angular/core';
import { from } from 'rxjs';
import { map, tap } from 'rxjs/operators';

export class MyType {
  constructor(private name: string) {}
}

@Component({
  selector: 'my-app',
  template: ''
})
export class AppComponent {
  observable$ = from([new MyType('obj1'), new MyType('obj2')]).pipe(
    map((value, index) => [value, index]),
    tap(([value, index]) => console.log(value, index))
  ).subscribe();
}

查看stackblitz,如果您将鼠标悬停在tap 的函数参数中的valueindex,当它应该理解value: MyType 和@987654328 时,它们都会被推断为number | MyType @。

如果我通过填写泛型来注释地图:map<MyType, [MyType, number]>(...,那么输入是正确的。

这是预期的行为吗? typescript 不应该在不必显式传递类型的情况下理解该元组吗?

我在本地使用 rxjs @ 6.4.0 和 typescript @ 3.8.3,但是 stackblitz 有更新的版本并且仍然存在这种行为。

【问题讨论】:

    标签: angular typescript generics types rxjs


    【解决方案1】:

    在您的 map 函数中,您返回的是一个数组,而不是元组。

    你可以使用as const强制元组类型:

    export class AppComponent {
      observable$ = from([new MyType('obj1'), new MyType('obj2')]).pipe(
        map((value, index) => [value, index] as const),
        tap(([value, index]) => console.log(value, index))
      ).subscribe();
    }
    

    Tuple Types:

    带有const 断言的数组文字将被推断为readonly 元组类型

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-17
      • 2022-09-29
      • 1970-01-01
      • 2019-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多