【发布时间】:2019-12-26 23:05:39
【问题描述】:
我正在尝试创建一个接受 actionType 作为键值的 TypeScript redux reducer,但是我正在努力为我的状态定义正确的接口。这样做时,我收到以下消息:
TS7053:元素隐式具有“any”类型,因为“string”类型的表达式不能用于索引“SampleState”类型。在“SampleState”类型上找不到带有“字符串”类型参数的索引签名。
当我的 reducer 接收到 actionType 时,如何正确地检查它的类型?谢谢,你可以看到下面的示例代码。
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;
【问题讨论】:
标签: typescript redux