Angular项目集成Redux实现JWT认证时store.ts报TS2769重载不匹配错误
Redux
createStore 抛出TS2769 类型不匹配错误排查 根本原因
TypeScript 报TS2769的核心逻辑是类型签名不匹配:
- Redux 内置的
Reducer<S, A>类型规范明确要求,reducer的第一个状态入参必须兼容undefined输入——这是Redux的设计逻辑:首次初始化store时,如果没有传入预加载状态,会给reducer传入undefined值,由reducer自行返回合法的初始状态 - 你定义的reducer函数将第一个参数硬绑定为非空的
appState类型,完全没有兼容undefined的输入场景,因此TypeScript校验时判定该函数不符合Reducer<appState, action>的类型要求,触发所有createStore重载的匹配失败
代码中关联的隐性问题(不修复即使过了类型校验也会运行报错)
- 自定义
action接口要求携带payLoad字段,但AuthService里所有dispatch调用都没有按这个结构传值,传入的是registeredUser、LoggedInUser等自定义键名,reducer根本读不到对应载荷 appState构造函数中读取sessionStorage的逻辑存在空值解析风险:当sessionStorage不存在user键时,sessionStorage.getItem("user")返回null,直接执行JSON.parse(null)会触发运行时错误- sessionStorage读写键名不匹配:reducer处理LogIn逻辑时写入的键是
item,但appState初始化时读取的键是user,永远读不到之前存的登录态 appState中user属性没有兼容null类型的定义,LogOut逻辑中把user设为null as any的写法会绕过类型校验,后续读取时容易触发空引用
分步修复方案
- 修正reducer的类型签名,兼容Redux要求的初始undefined输入
// reducer.ts 修正版 import { appState } from "./app-state"; import { actionType } from "./action-type"; import { action } from "./action"; export function reducer(currentState: appState | undefined, action: action): appState { // 首次调用时如果没有传入状态,返回合法的初始appState实例 if (!currentState) { return new appState(); } const newState = { ...currentState }; switch (action.type) { case actionType.getAllCars: newState.cars = action.payLoad; break; case actionType.Register: newState.user = action.payLoad; break; case actionType.LogIn: newState.user = action.payLoad; // 修正键名,和初始化读取的键保持一致 sessionStorage.setItem("user", JSON.stringify(newState.user)); break; case actionType.LogOut: newState.user = null; sessionStorage.removeItem("user"); break; } return newState; } - 修正store初始化逻辑,移除硬编码的预加载状态传值
// store.ts 修正版 import { createStore } from "redux"; import { reducer } from './reducer'; // 不需要手动传入new appState()作为预加载值,初始状态由reducer负责生成 export const store = createStore(reducer); - 修正appState的空值兼容逻辑与类型定义
// app-state.ts 修正版 import { carsModel } from '../models/cars.model'; import { userModel } from '../models/user.model'; export class appState { // 兼容null值,替代原来的null as any硬转 public user: userModel | null = null; public cars: carsModel[]; public constructor() { this.cars = []; // 增加空值判断,避免JSON.parse(null)报错 const savedUser = sessionStorage.getItem("user"); this.user = savedUser ? JSON.parse(savedUser) : null; } } - 修正所有dispatch的动作结构,严格匹配自定义action接口
以AuthService为例,替换原来的dispatch调用:// 原错误写法:store.dispatch({ type: actionType.Register, registeredUser }); // 修正为: store.dispatch({ type: actionType.Register, payLoad: registeredUser }); // 原错误写法:store.dispatch({ type: actionType.LogIn, LoggedInUser }); // 修正为: store.dispatch({ type: actionType.LogIn, payLoad: LoggedInUser });
内容的提问来源于stack exchange,提问作者Michael Sodovski
相关产品推荐
相关产品推荐

