【问题标题】:Return type of a `yield call``yield call`的返回类型
【发布时间】:2018-02-21 20:08:25
【问题描述】:

我注意到yield call 效果的结果在用作时输入为any

const data = yield call(f);

f() => Promise<number> 函数。

是我遗漏了什么还是 redux-saga 打字限制?

【问题讨论】:

    标签: typescript redux-saga


    【解决方案1】:

    检查this ongoing thread,tldr;这是打字稿限制

    【讨论】:

    • 请考虑在此处的链接中包含信息的要点。
    【解决方案2】:

    与此同时,您可以改用这个包:typed-redux-saga

    之前

    import { call, all } from "redux-saga/effects";
    ...
    // Api.fetchUser return User
    // but user has type any
    const user = yield call(Api.fetchUser, action.payload.userId);
    

    之后

    import { call, all } from "typed-redux-saga";
    ...
    // user now has the correct type User
    // NOTE: it's yield*, not yield
    const user = yield* call(Api.fetchUser, action.payload.userId);
    

    【讨论】:

      【解决方案3】:

      定义这些类型

      export type PromiseFn = (...args: any) => Promise<any>;
      export type GetT<T> = T extends Promise<infer N> ? N : any;
      export type GetFnResult<T extends PromiseFn> = GetT<ReturnType<T>>;
      
      

      然后

      const data: GetFnResult<typeof f> = yield call(f);
      

      【讨论】:

      • 我对@9​​87654323@ 的任何类型声明立即表示“不”。
      • ReturnType 也使用any
      【解决方案4】:

      你可以使用

      const data = (yield call(f)) as number
      

      【讨论】:

      • 这是对编译器的谎言。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-09
      • 2019-03-11
      • 2018-09-30
      • 1970-01-01
      • 2021-05-27
      • 2021-09-27
      • 2016-08-03
      相关资源
      最近更新 更多