【问题标题】:Typescript requires different return type depending on scenarioTypescript 根据场景需要不同的返回类型
【发布时间】:2020-10-12 11:32:22
【问题描述】:

您好,我是 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 from Type 'AxiosResponse&lt;any&gt;' 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
}

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

【问题讨论】:

  • 在第二个示例中,您已将返回类型标记为:Promise&lt;string&gt;,但由于您在函数内等待await axios....,因此它将解析为string 类型而不是Promise&lt;string&gt; .您的第三个示例也发生了类似的事情。只需执行return axios... 即可解决问题。还要在函数内部做await,函数本身应该是异步的,就像async function callApi(......
  • @boop_the_snoot 嗨,对不起,当我发布这个问题时,我错过了异步。我刚刚编辑。它应该有它。我不太明白return axios... 的意思,我该怎么做?你能详细说明吗?谢谢。

标签: typescript axios


【解决方案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`

【讨论】:

    猜你喜欢
    • 2021-09-19
    • 2012-04-03
    • 1970-01-01
    • 2022-11-27
    • 2019-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多