es6承诺的奇怪的打字错误

时间:2016-11-03 09:52:06

标签: javascript typescript es6-promise typescript-typings

代码

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)报告错误:

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"
        ]
    }
}

承诺的类型在node_modules/typescript/lib/lib.es2015.iterable.d.ts

中定义

但是,如果我不回复拒绝承诺:

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

没有错误。那么我怎样才能归还被拒绝的承诺?

2 个答案:

答案 0 :(得分:2)

您不会返回被拒绝的承诺,您只需抛出一个错误,这将导致承诺被拒绝:

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

答案 1 :(得分:0)

很抱歉回答一个老问题,但我认为您需要将return new Token(json)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));
    });
}