【问题标题】:Redux Saga: Type 'unknown' is not assignable to type 'ServerResponse'Redux Saga:类型“未知”不可分配给类型“ServerResponse”
【发布时间】:2020-11-02 20:11:29
【问题描述】:

问题陈述:

我无法为yield call() 指定类型。 yield 正在调用从服务器获取一些数据的 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) {
    ...
  }
};

【问题讨论】:

  • Generator 是一个泛型。你应该写类似serverSage(): Generator&lt;some, cool, types&gt;{} 的东西。我忘了哪个参数是哪个。
  • @zero298 如果您能告诉我有关参数的信息 ????
  • 你能发更多的serverSaga吗?它是否返回任何东西或产生任何其他yields?这些也会影响生成器的类型。如果您使用的是 VSCode,请删除返回类型并查看它自动生成的内容。以此作为回报的基础。
  • @zero298 是的,serverSaga 也确实产生了更多 yields。而且 VS 代码不会自动为函数生成返回类型。

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


【解决方案1】:

我相信您需要输入您的 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) {
    ...
  }
};

泛型生成器想要的实际类型可以用下面的例子来考虑。复杂的 sagas 会使泛型变得迟钝。

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;
}

【讨论】:

  • 这也没有帮助。 TS 在 yield 调用时抛出此错误:Type 'Promise&lt;ServerResponse&gt;' is missing the following properties from type 'SimpleEffect&lt;"CALL", CallEffectDescriptor&lt;ServerResponse&gt;&gt;': combinator, '@@redux-saga/IO', type, payload
  • @VinaySharma serverCall 接受参数吗?
  • 不,它没有。
【解决方案2】:

每个人都提供了很好的答案,但您也可以查看这个有助于缓解此类问题的库。我发现它在这种情况下非常有用。

【讨论】:

    【解决方案3】:

    我使用Generator&lt;AllEffect&lt;ForkEffect&lt;never&gt;&gt;&gt; 键入该函数。并且成功了。

    export default function* rootSaga(): Generator<AllEffect<ForkEffect<never>>> {
       const response = yield all([
        takeLatest(RepositoriesTypes.LOAD_REQUEST, load)
      ]);
      return response;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-08-30
      • 2021-10-19
      • 1970-01-01
      • 1970-01-01
      • 2021-05-18
      • 2020-04-02
      • 2019-06-02
      • 2021-02-28
      • 2018-01-04
      相关资源
      最近更新 更多