首页 > 解决方案 > 打字稿:“未知”类型的对象

问题描述

我有一个生成器函数foo(),我在其中使用fetch. 在收到来自API的响应后,我将其解析为JSON

打字稿抛出一个错误:Object of type 'unknown'在这一行 - >const msg = yield response.json();

function* foo(val: ValType): Generator {
    const response = yield fetch(endPoint, {
        method: 'POST',
        body: JSON.stringify(val),
    });

    if (response) {
        // typescript throws error
        // that type is unknown for
        // the response object
        const msg = yield response.json();
        return msg;
    }
}

标签: reactjstypescriptfetchgeneratorredux-saga

解决方案


错误是因为您没有声明类型为response. 使用必须像这样声明生成器函数的类型。

function* foo(arg): Generator<YieldType, ReturnType, ArgType> {
  // 
}

不需要分别声明收益类型、返回类型和参数类型,如果你这样声明,Typescript 可以推断出它们。

阅读更多


推荐阅读