I've been playing around with TypeScript recently and string literals work great with Redux actions and reducers. e.g:
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;
}
};
The problem I've stumbled upon is typing actions where the action name is imported from an npm module. So without any types, code would look like:
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;
}
}
How would I define the TypesScript type for SOME_ACTION? The type definition file exports SOME_ACTION as a string, so I cannot create the type as:
type SOME_ACTION = typeof SOME_ACTION;
In this case SOME_ACTION is a type of string rather than a string literal, so the reducer action matching doesn't work.