Reputation: 357
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { AppInfo } from '../models';
const initialState: AppInfo | null = null;
const appSlice = createSlice({
name: 'app',
initialState,
reducers: {
selectApp(state, action: PayloadAction<AppInfo>) {
return action.payload;
},
},
});
export const { selectApp } = appSlice.actions;
export default appSlice.reducer;
// models.ts
export type AppInfo = {
appName: string;
createDate: string;
develop: string;
op: string;
};
I want state.app
to be null
when redux starts, but later allow the user to select the app. However, I got a long TypeScript error on the reducer selectApp
. What does this error mean?
(method) selectApp(state: null, action: PayloadAction<AppInfo>): AppInfo
Type '(state: null, action: { payload: AppInfo; type: string; }) => AppInfo' is not assignable to type 'CaseReducer<null, { payload: any; type: string; }> | CaseReducerWithPrepare<null, PayloadAction<any, string, any, any>>'.
Type '(state: null, action: { payload: AppInfo; type: string; }) => AppInfo' is not assignable to type 'CaseReducer<null, { payload: any; type: string; }>'.
Type 'AppInfo' is not assignable to type 'void'.ts(2322)
Upvotes: 8
Views: 4784
Reputation: 357
https://www.reddit.com/r/reduxjs/comments/guns93/nullable_state_best_practice_typescript_redux/
export type AuthState = AppInfo | null;
const initialState = null as AuthState;
I found the answer in a reddit post. Seems null
will make typescript narrow the type to null
instead of AppInfo | null
. Use as
can solve the problem.
Upvotes: 12