带有多个返回类型的Typescript Promise无法分配

时间:2019-05-13 20:06:38

标签: typescript

我有一个带有一些功能的React组件,用于检索和创建文件夹记录。例如:

  handleCreateFolder = (params: object) => {
        return this._performRequest('post', params)
            .then((data: ListFolderType) => this._addFolder(data))
    };

   loadFolders() {
        return this._performRequest('get')
            .then((data: ApiResponseData<ListFolderType>) => this._setFolders(data))
    }

  _performRequest(method: string, ...args: Array<number | object>)  {
        return this.props.api[method](...args)
            .then((response: ApiResponse) => response.data as ApiResponseData<ListFolderType> | ListFolderType)
  }

api道具是Axios的包装,并公开了返回Promises的HTTP动词的功能。

我的_performRequest函数负责进行API调用并从data对象返回response密钥。这里的data可以是单个ListFolderType或类型为ApiResponseData<ListFolderType>的文件夹数组。

Typescript抱怨以下错误:

error TS2345: Argument of type '(data: ApiResponseData<ListFolderType>) => void' is not assignable to parameter of type '(value: ListFolderType | ApiResponseData<ListFolderType>) => void | PromiseLike<void>'.
  Types of parameters 'data' and 'value' are incompatible.
    Type 'ListFolderType | ApiResponseData<ListFolderType>' is not assignable to type 'ApiResponseData<ListFolderType>'.
      Type 'ListFolderType' is missing the following properties from type 'ApiResponseData<ListFolderType>': records, meta

    .then((data: ApiResponseData<ListFolderType>) => this._setFolders(data))

如何正确键入_performRequest函数可以返回两种类型之一,但是各自的handleCreateFolderloadFolders Promise函数仅接受一种类型?

0 个答案:

没有答案