首页 > 解决方案 > 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
}

但它没有用。知道为什么相同的返回结果需要不同的类型吗?我应该如何使它工作?

标签: typescriptaxios

解决方案


在这里分割你的例子:

// 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`

推荐阅读