I've been reading the documentation on using Redux with Typescript and I think I've got everything right, but my compiler is complaining regardless.
This is the problematic line:
/* Widget.tsx */
const error = useTypedSelector(state => state.error.widgetError)
// ^
// Object is of type 'unknown'. TS2571
useTypedSelector
is a recommended by the docs custom hook, so you won't have to typecast state
as RootState
whenever you use a selector.
/* store.ts* /
export type RootState = ReturnType<typeof store.getState>
/* hooks.ts */
import { TypedUseSelectorHook, useSelector } from 'react-redux'
import { RootState } from './store'
export const useTypedSelector: TypedUseSelectorHook<RootState> = useSelector
I don't understand what the problem is. My entire state tree is typed, and so is the state
argument in the callback. Hovering over the object in VS Code confirms this.
I've tried all sorts of typecasting to get around it, I still get the same error.
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
The only thing that worked was adding @ts-ignore
, but that kind of defeats half the purpose of using typescript to begin with.
I'm out of both smart and stupid ideas at this point. Halp please?
CodePudding user response:
If RootState is defined then const error = useSelector<RootState, ErrorState>((state) => state.error).widgetError; will do the job
CodePudding user response:
I can't reproduce this issue on codesandbox, nor in a new react app with the typescript template. It is most likely caused by (incorrectly?) adding ts to an existing js react app.