我一直在玩最近的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是一個字符串類型,而不是一個字符串,因此減速動作匹配不起作用。