[英]Typescript: Object of type 'unknown'
我有一个生成器函数foo()
,我在其中使用fetch
调用API 。 收到来自API的响应后,我将其解析为JSON 。
Typescript 抛出错误:此行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
声明类型。 使用必须像这样为 Generator 函数声明类型。
function* foo(arg): Generator<YieldType, ReturnType, ArgType> {
//
}
不需要分别声明 yield 类型、返回类型和参数类型,如果你这样声明,Typescript 可以推断它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.