Kevin
Kevin

Reputation: 290

Weird typings error for es6 promise

Code

getToken(authCode: string): Promise<Token> {
    return fetch(tokenUrl, { method: "POST" }).then(res => res.json()).then(json => {
        if (json["error"]) {
            return Promise.reject(json);
        }
        return new Token(json);
    });
}

Tsc(2.0.6) reports error:

xxx.ts(135,81): error TS2345: Argument of type '(json: any) => Promise<never> | Token' is not assignable to p
arameter of type '(value: any) => PromiseLike<never>'.                                                               
  Type 'Promise<never> | Token' is not assignable to type 'PromiseLike<never>'.                                      
    Type 'Token' is not assignable to type 'PromiseLike<never>'.                                                     
      Property 'then' is missing in type 'Token'.

Tsconfig.json:

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "lib": [
            "es6",
            "dom"
        ]
    }
}

Typings for promise is defined in node_modules/typescript/lib/lib.es2015.iterable.d.ts


However, if I do not return rejected Promise:

getToken(authCode: string): Promise<Token> {
    return fetch(tokenUrl, { method: "POST" }).then(res => res.json()).then(json => {
        return new Token(json);
    });
}

There will be no errors. So how can I return a rejected promise?

Upvotes: 2

Views: 2051

Answers (2)

Aziz Khambati
Aziz Khambati

Reputation: 368

Sorry for answering an old question, but I think you need to wrap return new Token(json) with Promise.resolve()

getToken(authCode: string): Promise<Token> {
  return fetch(tokenUrl, { method: "POST" })
    .then(res => res.json())
    .then(json => {
      if (json["error"]) {
        return Promise.reject(json);
      }
      // See this
      return Promise.resolve(new Token(json));
    });
}

Upvotes: 2

Nitzan Tomer
Nitzan Tomer

Reputation: 164129

You don't return the rejected promise, you simply throw an error which will cause the promise to be rejected:

getToken(authCode: string): Promise<Token> {
    return fetch(tokenUrl, { method: "POST" }).then(res => res.json()).then(json => {
        if (json["error"]) {
            throw new Error(json["error"]);
        }

        return new Token(json);
    });
}

Upvotes: 2

Related Questions