我有一个带有一些功能的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
函数可以返回两种类型之一,但是各自的handleCreateFolder
和loadFolders
Promise函数仅接受一种类型?