Working on react app with react-redux + react-toolkit and I ran into some typescript syntax that puzzled me.
export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch
export const useAppDispatch: () => AppDispatch = useDispatch
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector
What confused me is how '=' is being used in this line
export const useAppDispatch: () => AppDispatch = useDispatch
I assumed it was just casting the type, like in userInput as string
, but I changed the code around to export const useAppDispatch: () => useDispatch as AppDispatch
intellisense was throwing a ton of errors.
What is this line of code doing?
The part that's probably confusing you is the type annotation, which is the : () => AppDispatch
part. The :
indicates a type annotation, and the remainder is a function type that accepts no parameters and returns an AppDispatch
instance.
Breaking it down:
export const useAppDispatch
- Export a const called useAppDispatch
.: () => AppDispatch
- Which has the type () => AppDispatch
(a function accepting no parameters and returning an AppDispatch
instance).= useDispatch
- With useDispatch
as the value of the const.Once compiled to JavaScript, that will will be:
export const useAppDispatch = useDispatch;