从调用到获取键入Promise一般?

时间:2018-09-19 08:36:47

标签: javascript promise flowtype fetch-api

今天,在尝试通过调用fetch来键入Promise时遇到了一个小问题。

我有一个签名为callAPI的助手:

const apiCall = (url: string, requestOptions: RequestOptions = {}): Promise<{}>

现在,我在其他助手中使用它,其签名如下所示:

const getProps = async (
  // args
): Promise<{}> => {
  const { someProp } = await apiCall(
    // build query with args here 
  );

  return someProp;
};

不幸的是,flow对此表示抱怨,但我没有设法在此处键入回复。 Cannot call await with apiCall(...) bound to p because property someProp is missing in object type [1] in type argument R [2].

     /private/tmp/flow/flowlib_65ddbae/core.js
 [2] 583│ declare class Promise<+R> {

     apiCall.js
 [1]  43│ const apiCall = (url: string, requestOptions: RequestOptions = {}): Promise<{}> => {

有什么想法可以在此处 键入响应而不必在Response的{​​{1}}泛型中提供Response对象的所有可能的属性?谢谢 !

1 个答案:

答案 0 :(得分:1)

尝试使apiCall通用:

function apiCall<T>(url: string, requestOptions: RequestOptions = {}): Promise<T> {
  ...
}

调用此函数时,可以将期望的类型传递给它:

const { someProp } = await apiCall<{someProp: type_of_some_prop}>(...);