redux - ReduxToolkit+Typescript: ¿Qué tipo escribir para el tipo de estado del selector?
Digamos que estoy creando la siguiente porción:
import { createSlice } from '@reduxjs/toolkit';
interface ThoughtListDisplayOptions {
shouldShowCreateDate: boolean
}
interface DisplayOptions {
thoughtsList: ThoughtListDisplayOptions
}
interface OptionsState {
display: DisplayOptions
}
const initialState:OptionsState = {
display: {
thoughtsList: {
shouldShowCreateDate: true
}
}
};
const optionsSlice = createSlice({
name: 'options',
initialState: initialState,
reducers: {
setThoughtListDisplayOptions: (state, action) => {
state.display.thoughtsList = action.payload;
}
}
});
interface State {
options: OptionsState
}
export const selectThoughtListDisplayOptions = (state: State) => state.options.display.thoughtsList;
Y quiero mi selector:
export const selectThoughtListDisplayOptions = (state: State) => state.options.display.thoughtsList;
Para ser tipeado (es decir, cuando lo use quiero autocompletar, etc.). Entonces, en este caso añadí la interfaz de estado que solo contiene la porción en la que estoy trabajando. (Tengo otros slices de redux en esta aplicación)
interface State {
options: OptionsState
}
¿Es esta la forma adecuada de escribir el tipo del Estado? ¿O debería existir alguna interfaz central del Estado (u otra forma de tipar correctamente el selector)?
Respuesta #1
El selector State debería tener el tipo RootState que configuraste.
https://redux-toolkit.js.org/usage/usage-with-typescript#getting-the-state-type
import { combineReducers } from '@reduxjs/toolkit'; const rootReducer = combineReducers({}); export type RootState = ReturnType<typeof rootReducer>;
https://react-redux.js.org/using-react-redux/usage-with-typescript#typing-the-useselector-hook
// TS infers type: (state: RootState) => boolean const selectIsOn = (state: RootState) => state.isOn // TS infers `isOn` is boolean const isOn = useSelector(selectIsOn)const isOn = useSelector( (state: RootState) => state.isOn)
También puedes configurar una función useSelector con tipos bastante fácilmente:
import { useSelector, TypedUseSelectorHook } from "react-redux";
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
