Redux-Observable - Typescript error : "Property 'type' is missing in type '{}' but required in type"

Redux-Observable - Typescript error : "Property 'type' is missing in type '{}' but required in type"

我正在使用 redux-observable,我有一个我无法理解的 Typescript 错误,如果我在 rxjs 管道中有太多代码行,它似乎随机出现:

Type 'Observable<{}>' is not assignable to type 'Observable<{ type: "feed/PUSH"; payload: Profile; } | { type: "feed/POP"; } | { type: "feed/SWIPE"; payload: Swipe; } | { type: "feed/FETCH_NEXT_IDS"; } | { type: "feed/PUSH_NEXT_IDS"; payload: { nextIds: string[]; nextPage: number; }; } | { ...; } | { ...; } | { ...; }>'.
  Type '{}' is not assignable to type '{ type: "feed/PUSH"; payload: Profile; } | { type: "feed/POP"; } | { type: "feed/SWIPE"; payload: Swipe; } | { type: "feed/FETCH_NEXT_IDS"; } | { type: "feed/PUSH_NEXT_IDS"; payload: { nextIds: string[]; nextPage: number; }; } | { ...; } | { ...; } | { ...; }'.
    Property 'type' is missing in type '{}' but required in type '{ type: "feed/FETCH_NEXT_PROFILE"; }'.ts(2322)
action.d.ts(36, 5): 'type' is declared here.
index.d.ts(36, 26): The expected type comes from the return type of this signature.

这是有错误的代码。我在管道中添加了许多 tap 函数,以表明仅当我有太多 tap 时才会出现错误。如果我删除定义数量的 tap 错误似乎消失了。

export const swipeEpic: Epic<RootAction, RootAction, RootState> = action$ =>
  action$.pipe(
    filter(isOfType(SWIPE)),
    tap(nextIds => {
      console.log('fetch new ids result :');
      console.log(nextIds);
    }),
    tap(nextIds => {
      console.log('fetch new ids result :');
      console.log(nextIds);
    }),
    tap(nextIds => {
      console.log('fetch new ids result :');
      console.log(nextIds);
    }),
    tap(nextIds => {
      console.log('fetch new ids result :');
      console.log(nextIds);
    }),
    tap(nextIds => {
      console.log('fetch new ids result :');
      console.log(nextIds);
    }),
    tap(nextIds => {
      console.log('fetch new ids result :');
      console.log(nextIds);
    }),
    tap(nextIds => {
      console.log('fetch new ids result :');
      console.log(nextIds);
    }),
    tap(nextIds => {
      console.log('fetch new ids result :');
      console.log(nextIds);
    }),
    map(pop)
    // map(fetchNextProfile)
  );

我怀疑您所看到的在某种程度上与 RxJS 的 pipe() 实用程序仅对 pass in 9 operations.

具有类型安全支持这一事实有关

一旦超过该数字,它就会回退到类型安全性较低的签名,这可能会导致您的问题。它是否揭示了 RxJS、Redux Observable 的某种类型签名中的实际错误,或者您代码中的错误,或者它是否是 "just how it has to practically be",或者其他什么,我不能立即确定——抱歉!只是想顺道拜访,至少让您知道这很有可能是相关的。

您可以通过将您的操作分解为子流来避免这种情况,即不要管道化那么多的操作符。当然,必须将其作为建议提供不一定很好,无论如何这样做通常会有所帮助,以便为您的代码提供一些喘息的空间,并为以后维护此代码的其他开发人员提供上下文。


在 RxJS 中这样做的原因是因为 TypeScript(在撰写本文时)不支持可变参数泛型,也就是可变参数种类,尽管已经有 discussions around this for many many years.