如何使用Flow静态输入`window.fetch`的响应?

时间:2017-11-03 22:17:55

标签: flowtype

window.fetch来自JSON API的响应,我想键入检查我对响应的访问权限。例如:

type Result = {|+text: string, +metadata: {...}|};

type ApiResponse = Response & {|
  json: () => Result,
  text: null,
|};

const getResult = (): Promise<ApiResponse> => fetch(url);
// access to getResult().then(r => r.json()) is type checked against Result

但Flow无法用以下方式键入check:

Error: src/data/fetcher.js:18
                                             v-
 18: export type ApiResponse = Response & {|
 19:   json: () => Promise<Result>,
 20:
...:
 23: |};
     -^ exact type: object type. Inexact type is incompatible with exact type
987: declare function fetch(input: RequestInfo, init?: RequestOptions): Promise<Response>;
                                                                                ^^^^^^^^ Response. See lib: /private/tmp/flow/flowlib_211b7075/bom.js:987

我认为这是有道理的,因为它无法调整fetch的{​​{1}}返回类型与Promise<Response>的返回类型{{ 1}}。

如何约束getResult返回的东西是一个承诺?

1 个答案:

答案 0 :(得分:1)

  

如何约束getResult返回的东西是Promise?

将其键入Promise<Response>

Response.json() already resolves to any的类型,因此您可以断言它是您想要的任何类型:

declare class Response {
   ...
   json(): Promise<any>;
   ...
}

您可能遇到的下一个问题是&#34;如何让Flow知道调用json()时返回的类型?&#34;

输入您所期望的任何内容。像这样:

fetch(url)
  .then(res => res.json())
  .then((obj: Result) => {
        // Access your obj here
        // (Preferably with some level of checking to make sure
        //  the API returned a valid object)
      })