我一直在玩最近的TypeScript,字符串文字很适合Redux动作和缩减器。例如:如何在TypeScript中输入导入的redux动作?
const INCREMENT = "INCREMENT";
type INCREMENT = typeof INCREMENT;
const DECREMENT = "DECREMENT";
type DECREMENT = typeof DECREMENT;
interface IncrementAction {
type: INCREMENT;
}
interface DecrementAction {
type: DECREMENT;
}
type Actions = IncrementAction | DecrementAction;
const reducer = (state = 0, action: Actions) => {
switch (action.type) {
case INCREMENT:
return state + 1;
case DECREMENT:
return state + 1;
default:
return state;
}
};
我偶然发现的问题是,输入动作名称是从npm模块导入的。因此,如果没有任何类型,代码将如下所示:
import { SOME_ACTION } from 'npm-packaged-with-actions';
const reducer = (state = null, action) => {
switch (action.type) {
case SOME_ACTION:
return state + 1;
default:
return state;
}
}
如何为SOME_ACTION定义TypesScript类型?类型定义文件出口SOME_ACTION作为一个字符串,所以我不能创建类型为:
type SOME_ACTION = typeof SOME_ACTION;
在这种情况下SOME_ACTION是一个字符串类型,而不是一个字符串,因此减速动作匹配不起作用。