React-Redux useSelector typescript type for state
This might not be the answer but I use it like so:
const isLoggedIn = useSelector<IRootState, boolean>(state => state.user.loggedIn);
EDIT: Or use Peter's answer which is shorter/cleaner
const isLoggedIn = useSelector((state: IRootState) => state.user.loggedIn);
You can create your custom typed useSelector like so:
import {
useSelector as useReduxSelector,
TypedUseSelectorHook,
} from 'react-redux'
import { RootState } from 'app/redux/store'
export const useSelector: TypedUseSelectorHook<RootState> = useReduxSelector
where RootState
is the type of the store, usually defined as:
export type RootState = ReturnType<typeof rootReducer>
This is the method described in the definitely typed declaration.
Don't forget to install @types/react-redux
.
Here is the suggestion (more or less) from the redux docs:
import { RootState } from 'app/redux/store';
const isLoggedIn = useSelector(state: RootState => state.user.loggedIn);
The advantage over @Federkun's answer is that it is much simpler. The advantage over @alextrastero's answer is that I don't have to specify isLoggedIn's type manually.
-
Create
config.d.ts
-
Define your custom state
import 'react-redux'; import { ApplicationState } from '@store/index'; declare module 'react-redux' { interface DefaultRootState extends ApplicationState {} }