Sib*_*ini 5 javascript types fetch flowtype
我正在尝试在异步函数中使用fetch,但是流程正在抛出此错误
错误:(51,26)流程:承诺.这种类型是不符合工会:标识符类型的应用程序Promise
| T
await的类型参数
这是一个可以生成此错误的代码:
async myfunc() {
const response = await fetch('example.com');
return await response.json();
}
Run Code Online (Sandbox Code Playgroud)
我想输入响应 response.json
您可以使用Promise <T>
where T
所需的类型来注释函数的返回类型,或者将结果分配给具有显式类型注释的临时本地,然后返回该本地.然后将推断函数返回类型.
显式返回类型注释:
async myfunc(): Promise<{name: string}> {
const response = await fetch('example.com');
return await response.json();
}
Run Code Online (Sandbox Code Playgroud)
从显式注释的本地推断返回类型:
async myfunc() {
const response = await fetch('example.com');
const result: {name: string} = await response.json();
return result;
}
Run Code Online (Sandbox Code Playgroud)