Angular使用ngrx时报错'payload'不存在于'never'类型如何修复?
NgRx 报错
Property 'payload' does not exist on type 'never' 修复方案 错误原因
该报错是TypeScript类型推断失败导致:你使用ofType传入action类型字符串时,TS无法自动推导过滤后的action结构,默认将回调中的user变量推断为never类型,因此无法识别payload属性。
修复方案
方案1(推荐):ofType直接传入Action创建函数(无需手动指定类型)
NgRx的ofType支持直接传入createAction生成的Action构造函数,会自动完成类型推断,修改auth.effects.ts代码即可:
// 先从action文件引入对应的action创建函数 import { actionLogInSuccess } from './auth.actions'; effectLogInSuccess$ = createEffect( () => this.actions$.pipe( // 替换原来的AuthActionTypes.LOGIN_SUCCESS,直接传action构造函数 ofType(actionLogInSuccess), tap((user) => { console.log(user); localStorage.setItem('token', user.payload.token); this.router.navigateByUrl('/'); }) ), { dispatch: false } );
方案2:手动为回调参数指定类型
如果你需要保留传入type枚举的写法,可以手动给user参数加类型声明:
// 先引入action创建函数 import { actionLogInSuccess } from './auth.actions'; effectLogInSuccess$ = createEffect( () => this.actions$.pipe( ofType(AuthActionTypes.LOGIN_SUCCESS), // 用ReturnType获取action的返回类型,手动指定给user参数 tap((user: ReturnType<typeof actionLogInSuccess>) => { console.log(user); localStorage.setItem('token', user.payload.token); this.router.navigateByUrl('/'); }) ), { dispatch: false } );
优化建议
尽量不要将payload的类型设为any,可以自定义明确的接口保证类型安全,示例:
// auth.actions.ts interface LoginSuccessPayload { token: string; // 可补充其他返回字段比如用户信息 userInfo: { id: number; name: string; } } export const actionLogInSuccess = createAction( AuthActionTypes.LOGIN_SUCCESS, props<{ payload: LoginSuccessPayload }>() );
报错截图
内容的提问来源于stack exchange,提问作者Milena
相关产品推荐
相关产品推荐

