Typescript需要不同的返回类型,具体取决于场景
嗨,我是打字新手,需要对这个特殊的东西有一些了解 我返回以下格式的axios api响应:Typescript需要不同的返回类型,具体取决于场景,typescript,axios,Typescript,Axios,嗨,我是打字新手,需要对这个特殊的东西有一些了解 我返回以下格式的axios api响应: async function callApi(value:string):Promise<string>{ return await axios.post('/api/something', { key: value}) } 异步函数callApi(值:string):Promise{ return wait axios.post('/api/something',{key:value}
async function callApi(value:string):Promise<string>{
return await axios.post('/api/something', { key: value})
}
异步函数callApi(值:string):Promise{
return wait 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
}
异步函数callApi(值:string):Promise{
const result=await axios.post('/api/something',{key:value})
console.log(结果)
返回结果
}
它将抛出TS lint错误,表示类型“AxiosResponse”缺少类型“AxiosResponse”中的以下属性不可分配给类型“string”
我试过了
async function callApi(value:string):Promise<AxiosResponse<string>>{
const result = await axios.post('/api/something', { key: value})
console.log(result)
return result
}
异步函数callApi(值:string):Promise{
const result=await axios.post('/api/something',{key:value})
console.log(结果)
返回结果
}
但它不起作用。
知道为什么相同的返回结果需要不同的输入吗?我应该如何使其工作?在这里划分您的示例:
// 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>
}
在第二个示例中,您已将返回类型标记为
:Promise
,但由于您正在函数内部等待wait axios…
,因此它将解析为字符串
类型,而不是Promise
。同样的事情也发生在你的第三个例子中。只需执行返回axios…
即可解决问题。另外,要在函数内部执行wait
,函数本身应该是异步的,就像async function callApi一样(……
@boop\u the\u snoot嗨,很抱歉我在发布此问题时遗漏了异步。我刚刚编辑过。它应该有。我不太明白你所说的返回axios…
,我该怎么做?你能详细说明一下吗?谢谢。
function callApi(value:string): Promise<AxiosResponse<string>> {
return axios.post('/api/something', { key: value});
}
async function callApi(value:string): AxiosResponse<string> {
return await axios.post('/api/something', { key: value} );
}
async function callApi(value:string): AxiosResponse<string> {
const result = await axios.post('/api/something', { key: value} );
return result;
}
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`