2
votes
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);
        });
}

Got this code for retrieving data from API controller. When compiling it in ts, I am always getting this error:

Type 'Promise<void | LoginInfo>' is not assignable to type 'Promise<LoginInfo>'
Type 'void' is not assignable to type 'LoginInfo'

Here are my package versions:

"typescript": "2.5.2",
"@angular/compiler": "4.3.6"
"@angular/compiler-cli": "4.3.6"
1
If your catch catches an error, it's not re-thrown and nothing is returned, so the promise will then resolve to void - hence the Promise<void | LoginInfo> in the error. You need to decide what you want to do in the catch handler. At the moment, the typing of your function does not agree with what you are doing and an error is effected.cartant

1 Answers

8
votes

You need to return something on the error handling case or throw a new error. The method promises to return a LoginInfo but if an error occurs you return nothing, typescript protect you from accidentally returning nothing, if that is what you want you should return null explicitly:

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();
        });
}

As a side note, the async/await version may be more readable:

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) {
        this.handleError(error);
        return null;
    }
}