[英]Typescript Redux Type error of action.payload in reducer file
I am getting a type error in my reducers' file that my Property 'address' does not exist on type 'number |我的减速器文件中出现类型错误,我的属性“地址”不存在于类型“编号 | { connection: boolean; {连接:boolean; address: string;地址:字符串; }' . }' 。 I am using redux with typescript in my react application.我在我的反应应用程序中使用 redux 和 typescript。 I know it is due to the incorrect typesetting but I can't figure out how.我知道这是由于排版不正确,但我不知道如何。 I am using typescript with redux the first time and got stuck in this我第一次使用 typescript 和 redux 并陷入困境
Here is my actions file.这是我的动作文件。
interface IMetaMaskConnection{
type:typeof ActionType.CONNECT_META_MASK,
payload:{
connection:boolean,
address:string
}
}
interface IHourPassed{
type:typeof ActionType.HOUR_PASSED,
payload:number
}
export type Action = IMetaMaskConnection | IHourPassed
export const connectMetaMaskAction = (data:IMetaMaskConnection['payload']):Action => ({
type: ActionType.CONNECT_META_MASK,
payload:data
});
export const setHourPassed = (data:IHourPassed['payload']):Action => ({
type: ActionType.HOUR_PASSED,
payload:data
});
export const reducer= (state:IState=initialState, action:Action):IState=> { const {type, payload}=action; switch(type){ case ActionType.CONNECT_META_MASK: return {...state, address:payload.address, connection:payload.connection } case ActionType.HOUR_PASSED: return {...state, hourPassed:payload } default: return state; } } export type State= ReturnType<typeof reducer>
This is my error screenshot.这是我的错误截图。
The first issue here is that you should really be using our official Redux Toolkit package and its createSlice
API for writing your reducers.这里的第一个问题是你真的应该使用我们的官方 Redux 工具包 package 及其createSlice
API来编写你的减速器。 createSlice
will also generate action creators for you automatically. createSlice
还会自动为您生成动作创建者。
See the Redux TS Quick Start guide for details on how to set up and use RTK with TypeScript.有关如何通过 TypeScript 设置和使用 RTK 的详细信息,请参阅Redux TS 快速入门指南。
Beyond that, the actual error here is that you told TS "the action
can be one of these two types", but the destructuring of {type}
means that TS can't narrow down the TS type of the action object inside the case
statement (although TS 4.5 did just improve that behavior).除此之外,这里的实际错误是您告诉 TS“ action
可以是这两种类型之一”,但是{type}
的解构意味着 TS 无法在case
语句中缩小动作 object 的 TS 类型(尽管 TS 4.5 确实改善了这种行为)。 So, TS still thinks it could be either of those two action types.所以,TS 仍然认为它可能是这两种动作类型中的任何一种。
But all those problems would go away if you switch to using createSlice
.但是,如果您切换到使用createSlice
,所有这些问题都会 go 消失。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.