【问题标题】:Typescript: Object of type 'unknown'打字稿:“未知”类型的对象
【发布时间】:2020-03-18 09:10:17
【问题描述】:

我有一个 generator 函数 foo(),我在其中使用 fetch 调用 API。 从 API 收到 response 后,我将其解析为 JSON

Typescript 抛出错误:Object of type 'unknown' in this line -> 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;
    }
}

【问题讨论】:

  • foo 的消费者可以yield 为所欲为。你的意思是用await 代替yield,用async 代替*
  • @CertainPerformance 所说的:typescriptlang.org/play/?target=99#code/…
  • 您应该使用 asyncawait 只是为了确保在测试之前获取数据是否有任何结果
  • @CertainPerformance 我并不是要使用await,因为我在Redux Saga 中使用foo。我不确定 async/await 是否可以在 Redux Saga 中使用,因为只能使用生成器函数。
  • @besartm 我无法使用 async/await,因为我正在使用 Redux Saga

标签: reactjs typescript fetch generator redux-saga


【解决方案1】:

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

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

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

Read more

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-25
    • 1970-01-01
    • 2022-01-01
    • 2018-05-30
    • 2018-09-15
    • 2020-06-10
    • 1970-01-01
    相关资源
    最近更新 更多