打字稿根据情况需要不同的返回类型

时间:2020-10-12 02:41:51

标签: typescript axios

嗨,我是打字稿新手,需要对此特殊知识有所了解。

我将以以下格式返回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错误,提示类型'AxiosResponse'缺少Type '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
}

但是没用。 知道为什么相同的返回结果需要不同的输入吗?我该如何运作?

1 个答案:

答案 0 :(得分:1)

在此处说明您的示例:

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