Cab*_*age 8 typescript reactjs redux redux-toolkit
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;
};
Run Code Online (Sandbox Code Playgroud)
我希望state.app在nullredux 启动时,但稍后允许用户选择应用程序。然而,我在减速器上遇到了一个很长的 TypeScript 错误selectApp。这个错误是什么意思?
(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)
Run Code Online (Sandbox Code Playgroud)
Cab*_*age 11
https://www.reddit.com/r/reduxjs/comments/guns93/nullable_state_best_practice_typescript_redux/
export type AuthState = AppInfo | null;
const initialState = null as AuthState;
Run Code Online (Sandbox Code Playgroud)
我在 Reddit 帖子中找到了答案。似乎null会使打字稿将类型缩小为null而不是AppInfo | null。使用as即可解决问题。
| 归档时间: |
|
| 查看次数: |
4355 次 |
| 最近记录: |