打字稿中的固定类型

时间:2019-10-22 19:22:06

标签: javascript typescript ecmascript-6 types

我有一种使用外部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上收到错误消息

2 个答案:

答案 0 :(得分:1)

这种方法使事情变得比您需要做的要困难。如果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的情况。您只需要确保某些东西能够捕获错误即可。

答案 1 :(得分:0)

您最有可能看到此错误,因为您在tsconfig中将TypeScript设置为strict模式。这样可以启用另一个标志strictNullChecks,这又迫使类型anyundefined仅可分配给自己,因为您可以读取here

在您的代码中,getStatus的签名为public async getStatus(id: string): Promise<APIRes | undefined>,因此返回的类型可以为Promise<undefined>,这意味着您需要检查它是否未定义

public async getListOfResults(id: string) {
        try {

            const getStatus = await this.getStatus(id)
            if (getStatus // Check if getStatus is NOT undefined before accessing it's properties (so it can only be Promise<APIRes>)
                && (getStatus.status === 'Queue' || getStatus.status === 'Progr')) {
                ...//MORE CODE
            }

            const result = await getRequest(`${this.URL}/endpoint/${id}/result`)

            return result.data
        } catch (err) {
            errorHandler(err)
        }
    }