Redux useSelector 与 Typescript:为什么类型的对象是“未知”?

Sum*_*mer 8 typescript reactjs redux

我一直在阅读有关将 Redux 与 Typescript 结合使用的文档,我认为我一切都正确,但无论如何我的编译器都会抱怨。

这是有问题的行:

// Widget.tsx

const error = useTypedSelector(state => state.error.widgetError)
//                                      ^
// Object is of type 'unknown'.  TS2571
Run Code Online (Sandbox Code Playgroud)

useTypedSelector是文档自定义挂钩推荐的,因此您不必stateRootState使用选择器时那样进行类型转换。

// store.ts
export type RootState = ReturnType<typeof store.getState>
Run Code Online (Sandbox Code Playgroud)
// hooks.ts
import { TypedUseSelectorHook, useSelector } from 'react-redux'
import { RootState } from './store'

export const useTypedSelector: TypedUseSelectorHook<RootState> = useSelector
Run Code Online (Sandbox Code Playgroud)

我不明白问题是什么。我的整个状态树都已键入,state回调中的参数也是如此。将鼠标悬停在 VS Code 中的对象上可以确认这一点。

是的。 这就是状态树。

我尝试了各种类型转换来解决它,但仍然遇到相同的错误。

const error = useSelector((state: RootState) => state.error.widgetError) // no
const error = useSelector<RootState, string | null>(state => state.error.widgetError) // nup
const error = useTypedSelector(state => (state as RootState).error.widgetError) // nuh-uh
Run Code Online (Sandbox Code Playgroud)

唯一有效的方法是添加@ts-ignore,但这就违背了使用打字稿的一半目的。

在这一点上,我既没有聪明的想法,也没有愚蠢的想法。请停下来?

Sum*_*mer 1

我无法在codesandbox 上重现此问题,也无法在带有打字稿模板的新反应应用程序中重现此问题。这很可能是由于(错误地?)将 ts 添加到现有的 js React 应用程序引起的。