Reputation: 83279
I'm trying to use FlowType for the first time, and I'm running into trouble with assigning constant values as type literals. How can I change the following to prevent using the same string values in both the constant definition and the type declaration?
// @flow
export const INITIAL = 'INITIAL'
export const LOADING = 'LOADING'
export const LOADED = 'LOADED'
export const FAILED = 'FAILED'
export type State = 'INITIAL' | 'LOADING' | 'LOADED' | 'FAILED'
Upvotes: 1
Views: 411
Reputation: 16435
Short answer: you can't (AFAIK)
Long answer: you should restructure your program to get rid of those constants. If you look at the benefits of those constants (i.e. What is the point of the constants in redux?)
It helps keep the naming consistent because all action types are gathered in a single place.
Sometimes you want to see all existing actions before working on a new feature. It may be that the action you need was already added by somebody on the team, but you didn’t know.
The list of action types that were added, removed, and changed in a Pull Request helps everyone on the team keep track of scope and implementation of new features.
If you make a typo when importing an action constant, you will get undefined. This is much easier to notice than a typo when you wonder why nothing happens when the action is dispatched.
all the same things can be achieved with the variant type.
If you're using redux, you can see how they eliminate the constants using flow in the docs about using redux with flow:
// @flow
type State = { +value: boolean };
type FooAction = { type: "FOO", foo: boolean };
type BarAction = { type: "BAR", bar: boolean };
type Action = FooAction | BarAction;
function reducer(state: State, action: Action): State {
switch (action.type) {
case "FOO": return { ...state, value: action.foo };
case "BAR": return { ...state, value: action.bar };
default:
(action: empty);
return state;
}
}
which not only makes sure you didn't make typos, and what not, but the (action: empty) at the end ensures you handled all cases.
Upvotes: 1