Redux Saga:类型“未知”不可分配给类型“ ServerResponse”

时间:2020-07-13 15:27:14

标签: javascript reactjs typescript react-redux redux-saga

问题陈述:

我无法为yield call()指定类型。收益率正在调用 API ,该API从服务器获取一些数据。的数据类型为 ServerResponse 。我想做的是指定类型,如下所示:

const response: ServerResponse = yield serverCall();

但是我Typescript抛出此错误:Redux Saga: Type 'unknown' is not assignable to type 'ServerResponse'

代码:

function* serverSaga(): Generator {
  try {
    // TS throws error here;
    const response: ServerResponse = yield serverCall();
    ...
    ...
  } catch (err) {
    ...
  }
}

const serverCall = async (): Promise<ServerResponse> => {
  try {
    const response =  await ...
    return response;
  } catch (err) {
    ...
  }
};

2 个答案:

答案 0 :(得分:1)

每个人都提供了很好的答案,但是您也可以研究可以帮助减轻此类问题的图书馆。我发现它在这种情况下非常有用。

答案 1 :(得分:0)

我相信您需要输入Generator泛型,并且还应该使用call来实际调用异步函数:

import {
  call,
  CallEffect
} from "redux-saga/effects";

function* serverSaga(): Generator<CallEffect<ServerResponse>, void, never> {
  try {
    // TS throws error here;
    const response: ServerResponse = yield call(serverCall);
    ...
    ...
  } catch (err) {
    ...
  }
}

const serverCall = async (): Promise<ServerResponse> => {
  try {
    const response =  await ...
    return response;
  } catch (err) {
    ...
  }
};

可以通过以下示例考虑通用生成器所需的实际类型。复杂的虎杖可以使这种钝角变得普遍。

type MyGen = Generator<
  number, // Outgoing (what you might yield)
  boolean, // What could be returned
  string // Incoming (left side of yield)
>;

function* MySaga(): MyGen {
  let outgoing = 0;
  while (outgoing < 10) {
    outgoing++;
    const incoming: string = yield outgoing;
    console.log(incoming);
  }
  return true;
}