reactjs - 打字稿:“未知”类型的对象
问题描述
我有一个生成器函数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;
}
}
解决方案
错误是因为您没有声明类型为response
. 使用必须像这样声明生成器函数的类型。
function* foo(arg): Generator<YieldType, ReturnType, ArgType> {
//
}
不需要分别声明收益类型、返回类型和参数类型,如果你这样声明,Typescript 可以推断出它们。
推荐阅读
- c# - 如果我按 Enter 键,如何在多行文本框中将最后一行文本串起来
- python - 用 cv2.imwrite 保存 BGR 图像
- php - CLI 和 Apache() 上 exec() 的区别
- angular - 如何正确使用 PrimeNG 的 Dropdown
- numpy - 3D 绘图未显示
- python - 20 个新闻组数据集包含大约 18000 个新闻组帖子,而 sklearn 只加载了大约一半的数据集,这是为什么呢?
- javascript - 如何根据查询更新 Firestore 上的文档
- c# - JSON:API 规范与使用 NewtonSoft 序列化对象
- c++ - 调用重载的构造函数会产生歧义错误 C++
- git - 从 Jenkins 运行 Katalon Studio 时构建失败