I am currently grappling with creating a TypeScript redux reducer that can effectively handle different action types. However, I am facing difficulties in defining the appropriate interface for my state, leading to the error message below:
TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'SampleState'. No index signature with a parameter of type 'string' was found on type 'SampleState'.
https://i.sstatic.net/Y2VvL.png
Can someone guide me on how to correctly implement type checking for my reducer when handling various action types? Below is a snippet of the code for reference.
sampleActionTypes.ts:
export const FOO = 'FOO';
export const BAR = 'BAR';
export const TURN_ON = 'TURN_ON';
export const TURN_OFF = 'TURN_OFF';
interface TurnOn {
type: typeof TURN_ON;
actionType: string;
}
interface TurnOff {
type: typeof TURN_OFF;
actionType: string;
}
export type Types = TurnOn | TurnOff;
sampleReducer.ts:
import { BAR, FOO, TURN_OFF, TURN_ON, Types } from './sampleActionTypes';
export interface SampleState {
[FOO]: {
toggle: boolean;
};
[BAR]: {
toggle: boolean;
};
}
const initialState: SampleState = {
[FOO]: {
toggle: false,
},
[BAR]: {
toggle: false,
},
};
const sampleReducer = (state = initialState, action: Types): SampleState => {
switch (action.type) {
case TURN_ON:
return {
...state,
[action.actionType]: {
...state[action.actionType],
toggle: true,
},
};
case TURN_OFF:
return {
...state,
[action.actionType]: {
...state[action.actionType],
toggle: false,
},
};
default:
return state;
}
};
export default sampleReducer;