类型“无效”不能分配给对象

jen*_*fad 2 typescript

export class LoginInfo {
    userName: string;
    password: string;
} 

public getLoginInfo(id: number): Promise<LoginInfo> {
    return this.http.get(this.url + id + '/' + '/loginInfo')
        .toPromise()
        .then(response => response.json() as LoginInfo)
        .catch((error: Response) => {
            this.handleError(error);
        });
}
Run Code Online (Sandbox Code Playgroud)

获得了用于从API控制器检索数据的代码。在ts中进行编译时,总是会出现以下错误:

Type 'Promise<void | LoginInfo>' is not assignable to type 'Promise<LoginInfo>'
Type 'void' is not assignable to type 'LoginInfo'
Run Code Online (Sandbox Code Playgroud)

这是我的软件包版本:

"typescript": "2.5.2",
"@angular/compiler": "4.3.6"
"@angular/compiler-cli": "4.3.6"
Run Code Online (Sandbox Code Playgroud)

Tit*_*mir 6

您需要在错误处理案例中返回某些内容或引发新错误。该方法承诺返回a,LoginInfo但是如果发生错误,则不返回任何内容,打字稿可以保护您免于意外不返回任何内容,如果那是您想要的,则应明确返回null:

public getLoginInfo(id: number): Promise<LoginInfo> {
    return this.http.get(this.url + id + '/' + '/loginInfo')
        .toPromise()
        .then(response => response.json() as LoginInfo)
        .catch((error: Response) => {
            this.handleError(error);
            // return null;
            throw new Error();
        });
}
Run Code Online (Sandbox Code Playgroud)

附带说明一下,异步/等待版本可能更具可读性:

public async getLoginInfo(id: number): Promise<LoginInfo> {
    try{
        let response = await this.http.get(this.url + id + '/' + '/loginInfo').toPromise();
        return response.json() as LoginInfo;
    } catch (error: Response) {
        this.handleError(error);
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)