Flow vs TypeScript动作创建者(Redux)

时间:2018-03-18 09:43:47

标签: javascript typescript redux flowtype

我试图弄清楚如何使用Flow实现Redux的类型注释。

使用TypeScript:

const PLAY = 'PLAY';
const RUN = 'RUN';

class PlayAction {
    readonly type = PLAY;
    constructor(public payload: string) {}
}

class RunAction {
    readonly type = RUN;
    constructor(public payload: boolean) {}
}

type Actions = PlayAction | RunAction;

function dummyReducer(state: any, action: Actions) {
    switch(action.type) {
        case PLAY: {
            const typeTest = action.payload; // type: string 
            break;
        }
        case RUN: {
            const typetest = action.payload; // type: boolean
            break;
        }
    }
}

在流文档中,我找到了这个示例: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;
  }
}

Flow方法存在的重大问题:

1)在2个地方使用字符串,所以拼错错误是不好的做法。

每次我想要更改动作类型值时,

2)都无法维护在2个位置更改字符串。

如何使用Flow解决此问题?有什么想法吗?

1 个答案:

答案 0 :(得分:2)

我找到了一些答案,但它不起作用, 再次,你不能与集体行动创作者合作。 :/

type _ExtractReturn<B, F: (...args: any[]) => B> = B;
export type ExtractReturn<F> = _ExtractReturn<*, F>;

行动档案//

export const SET_NAME = 'SET_NAME';
export const SET_AGE = 'SET_AGE';
const setName = (name: string) => {
    return {type: SET_NAME, payload: name}
}

const setAge = (age: number) => {
    return {type: SET_AGE, payload: age}
}
export type Actions =
    ExtractReturn<typeof setName> |
    ExtractReturn<typeof setAge>

enter image description here

信用:Shane Osbourne

Redux & Flow-type