【发布时间】:2020-07-07 19:31:16
【问题描述】:
我有以下 redux-thunk 动作创建者:
function updateInitiator(form_request_id, { to_recipient }) {
return (dispatch) => {
const url = `/some/url`;
const data = { to_recipient };
return fetch(url, { method: 'PUT', body: JSON.stringify(data) }).then(() => {
dispatch(fetchResponses());
});
};
}
然后我声明函数的类型:
type UpdateInitiator = typeof updateInitiator;
我正在尝试导出绑定 thunk 操作的类型。简而言之,当action creator在react-redux中被“绑定”时,它会自动调用dispatch返回的函数,然后返回that内部函数的返回结果。我正在尝试为这种行为声明一个类型。如果我在没有泛型的情况下这样做,它会起作用:
type BoundUpdateInitiator = (...args: Parameters<UpdateInitiator>) => ReturnType<ReturnType<UpdateInitiator>>;
但是当我尝试为任何绑定函数声明一个泛型类型时,我遇到了一些麻烦:
type BoundThunk<T> = (...args: Parameters<T>) => ReturnType<ReturnType<T>>;
type BoundUpdateInitiator = BoundThunk<UpdateInitiator>;
这给了我错误:
error TS2344: Type 'T' does not satisfy the constraint '(...args: any) => any'.
236 type BoundThunk<T> = (...args: Parameters<T>) => ReturnType<ReturnType<T>>;
~
error TS2344: Type 'ReturnType<T>' does not satisfy the constraint '(...args: any) => any'.
Type 'unknown' is not assignable to type '(...args: any) => any'.
Type '{}' provides no match for the signature '(...args: any): any'.
236 type BoundThunk<T> = (...args: Parameters<T>) => ReturnType<ReturnType<T>>;
~~~~~~~~~~~~~
error TS2344: Type 'T' does not satisfy the constraint '(...args: any) => any'.
236 type BoundThunk<T> = (...args: Parameters<T>) => ReturnType<ReturnType<T>>;
~
我可以隐约理解T 可能不是函数,同样ReturnType<T> 也可能不是函数,而这种泛型类型可能不考虑这些情况。但是,我无法理解如何 解释它们。理想情况下不允许他们。有什么建议吗?
【问题讨论】:
-
这就是泛型类型约束的用途。查看
ReturnType<T>和Parameters<T>的定义,您会立即看到要写什么。例如:type BoundThunk<T extends (...args: any[]) => any> = (...args: Parameters<T>) => stuff -
@AluanHaddad 成功了。如果你想回答我会标记为正确的。
标签: reactjs typescript redux-thunk