I am getting a type error in my reducers' file that my Property 'address' does not exist on type 'number | { connection: boolean; address: string; }'. I am using redux with typescript in my react application. 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
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
});
This is my reducer.
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.
CodePudding user response:
The first issue here is that you should really be using our official Redux Toolkit package and its createSlice
API for writing your reducers. createSlice
will also generate action creators for you automatically.
See the Redux TS Quick Start guide for details on how to set up and use RTK with TypeScript.
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). So, TS still thinks it could be either of those two action types.
But all those problems would go away if you switch to using createSlice
.