typescript - Typescript 根据场景需要不同的返回类型
问题描述
嗨,我是打字稿的新手,需要对这些特殊的东西有所了解。
我正在返回具有以下格式的 axios api 响应:
async function callApi(value:string):Promise<string>{
return await axios.post('/api/something', { key: value})
}
这行得通。但是如果我想将它重构为
async function callApi(value:string):Promise<string>{
const result = await axios.post('/api/something', { key: value})
console.log(result)
return result
}
它会抛出 TS lint 错误,说 Type 'AxiosResponse' is missing the following properties fromType 'AxiosResponse<any>' is not assignable to type 'string'
我试过了
async function callApi(value:string):Promise<AxiosResponse<string>>{
const result = await axios.post('/api/something', { key: value})
console.log(result)
return result
}
但它没有用。知道为什么相同的返回结果需要不同的类型吗?我应该如何使它工作?
解决方案
在这里分割你的例子:
// Function is ALWAYS expected to return Promise<string>
async function callApi(value:string): Promise<string> {
const result = await axios.post('/api/something', { key: value} )
// Because you have awaited here ^^^, its converted to `AxiosResponse<string>` instead of `Promise<string>`
return result
// Thus, ^^^ `result` is of type 'AxiosResponse<string>', which contradicts function's expected return type, ie Promise<string>
}
您的需求可以用多种方式编写,如下所示:
示例 1:
function callApi(value:string): Promise<AxiosResponse<string>> {
return axios.post('/api/something', { key: value});
}
示例 2:
async function callApi(value:string): AxiosResponse<string> {
return await axios.post('/api/something', { key: value} );
}
示例 3:
async function callApi(value:string): AxiosResponse<string> {
const result = await axios.post('/api/something', { key: value} );
return result;
}
示例 4:
async function callApi(value:string): string {
const result = await axios
.post('/api/something', { key: value} )
.then(r => r.json()); // This will auto-convert to expected return type
return result; // its type is `string`, instead of `AxiosResponse<string>`
}
上面给出的所有示例的用法:
callApi('test').then(...);
// OR
const resp = await callApi('test'); // to use like this, calling function should also be marked `async`
推荐阅读
- javascript - 在 Teams 平台上更新 BotFramework v4 中的活动
- javascript - 按字母数字对对象数组进行排序
- android - 如何知道图像是否为灰度?
- linux - Linux Kernel 5.0.1 中为 x86 架构定义的系统调用 ID 在哪里?
- macos - MacOS 莫哈韦沙漠。Xlib 编译时出错。致命错误:找不到“X11/Xlib.h”文件
- vba - 如何使用组合框填充 MS-Access 子表单中的多个字段?
- json.net - 为什么 Newtonsoft Schema Validator 无法识别 OAS3 可为空的属性?
- haskell - Haskell Tasty.HUnit:如何使用 IO 运行多个测试
- javascript - 单击带有香草JS的菜单链接时如何隐藏下拉菜单?
- jboss-eap-7 - 将认证从 JBoss EAP 6.4 迁移到 JBoss EAP 7.0