我有一个使用外部API数据的方法:
public async getStatus(id: string): Promise<APIRes | undefined> {
try {
const result = await getRequest(`${this.URL}/endpoint/${id}`)
const response: APIRes = result.data
return response
} catch (err) {
errorHandler(err)
}
}
APIRes的界面如下:
export interface APIRes{
version: string,
status: string,
uuid: string,
time: string
}
问题是当我尝试从另一种方法调用getStatus时:
public async getListOfResults(id: string) {
try {
const getStatus = await this.getStatus(id)
if (getStatus.status === 'Queue' || getStatus.status === 'Progr') {
...//MORE CODE
}
const result = await getRequest(`${this.URL}/endpoint/${id}/result`)
return result.data
} catch (err) {
errorHandler(err)
}
}
我在getStatus.status上得到
Object is possibly undefined
。现在,我知道了为什么会发生这种情况(因为getStatus方法可能返回未定义的值),但是不确定如何在不添加nostrict
标志的情况下进行最佳修复。如果删除
<| undefined>
的返回类型中的getStatus
,我会得到Function lacks ending return statement and return type does not include 'undefined'.ts(2366)`
如果我尝试将其从undefined更改为void,我仍然在
getStatus.status
上收到错误消息 最佳答案
这种方法使事情变得比您需要做的事情困难。如果getStatus
出现错误,是否要将其解析为undefined
?如果是这样,那么调用它的所有内容都必须检查该未定义的。为什么不让呼叫者查找引发的错误呢?只需让错误冒泡,或者执行错误处理程序并重新抛出:
public async getStatus(id: string): Promise<APIRes> {
try {
const result = await getRequest(`${this.URL}/endpoint/${id}`)
const response: APIRes = result.data
return response
} catch (err) {
errorHandler(err)
throw err;
}
}
现在,这只会解析为
APIRes
,而您不必处理undefined
的情况。您只需要确保某些内容能够捕获错误即可。