我正在尝试创建一个带有类型的可重用useReducer钩子。
这是我目前的代码:
type State<T> = {
data?: T
isLoading: boolean
error?: string
}
type Action<T> =
| { type: "request" }
| { type: "success"; results: T }
| { type: "failure"; error: string }
function reducer<T>(state: State<T>, action: Action<T>): State<T> {
switch (action.type) {
case "request":
return { isLoading: true }
case "success":
return { isLoading: false, data: action.results }
case "failure":
return { isLoading: false, error: action.error }
}
}
export function useFetchState<T>() {
return useReducer(reducer<T>, {isLoading: false});
}如您所见,钩子应该用于保持获取状态,但是数据应该是动态的,因此可以在不同的上下文中使用:
const [videoFetch, dispatchVideo] = useFetchState<Video[]>()
const [userFetch, dispatchUser] = useFetchState<User[]>()我的问题是,表达式reducer<T>由于错误而失败:(26,20) TS2345:类型'boolean‘的参数不能分配给’Reducer‘类型的参数,但是没有指定T,数据类型是未知的。
我不确定,这种情况是如何在TypeScript土地上被称为,所以我希望有人能向我解释,如果和如何我可以实现,我想要什么。
非常感谢。
发布于 2019-08-24 18:54:24
reducer<T>在语法上不是无效的。reducer就是reducer。没有像reducer<T>这样的东西。编译器将其理解为reducer < T > (比较运算符),它认为,当作为表达式完成时,它很可能是一个布尔值。这就是为什么它抱怨“boolean类型的参数不能分配给Reducer类型的参数”--编译器在应该出现Reducer类型的值(仅是reducer变量)的位置发现布尔值或布尔值怀疑。
不传递泛型参数也是错误的。例如,videoFetch的类型推断是错误的:videoFetch被推断为State<{}> (在最近的版本中可能是State<unknown> )。但我不能百分之百地肯定这一点)。
那么泛型参数T应该在哪里呢?注意,类型推断实际上发生在useReducer上。因此,我们只需要手动提供正确的useReducer类型参数。
export function useFetchState<T>() {
return useReducer<Reducer<State<T>, Action<T>>>(reducer, { isLoading: false });
}在这种情况下,您可以检查是否正确推断了videoFetch的类型。所有其他变量的类型也是如此。
https://stackoverflow.com/questions/57636760
复制相似问题