我有以下代码:
src \ types.js
export type TLoadIndex = { type: string, index: number }
export type TLoadAll = { type: string }
export type TDeleteAll = { type: string }
export type TAction = TLoadIndex | TLoadAll | TDeleteAll;
export type TPlane = {
title?: string,
caption?: string,
text?: string,
image: string,
};
src \ store \ plane \ reducer.js
import planeList from './planeList';
import { LOAD_INDEX, LOAD_ALL, DELETE_ALL } from './actions';
import type { TLoadIndex, TLoadAll, TDeleteAll, TAction, TPlane } from '../../types';
export default function (currentList: TPlane[] = [], action: TAction): TPlane[] {
let newList: TPlane[] = currentList;
switch (action.type) {
case LOAD_INDEX:
if (planeList[action.index])
newList = [...currentList, planeList[action.index]];
break;
case LOAD_ALL:
newList = planeList;
break;
case DELETE_ALL:
newList = [];
break;
}
return newList;
}
我的问题是:,当我运行以下命令时:
> npm run flow
我收到以下flow
错误:
Error -------------- src/store/plane/reducer.js:9:25
Cannot get action.index because:
- property index is missing in TDeleteAll [1].
- property index is missing in TLoadAll [1].
[1] 5| export default function (currentList: TPlane[] = [], action: TAction): TPlane[] {
6| let newList: TPlane[] = currentList;
7| switch (action.type) {
8| case LOAD_INDEX:
9| if (planeList[action.index])
10| newList = [...currentList, planeList[action.index]];
11| break;
12| case LOAD_ALL:
Error -------------- src/store/plane/reducer.js:10:49
Cannot get action.index because:
- property index is missing in TDeleteAll [1].
- property index is missing in TLoadAll [1].
[1] 5| export default function (currentList: TPlane[] = [], action: TAction): TPlane[] {
6| let newList: TPlane[] = currentList;
7| switch (action.type) {
8| case LOAD_INDEX:
9| if (planeList[action.index])
10| newList = [...currentList, planeList[action.index]];
11| break;
12| case LOAD_ALL:
13| newList = planeList;
我要指出的是,我不想将属性index
添加到以下类型:{ TLoadAll, TDeleteAll }
,因为该属性只需要绑定到类型:TLoadIndex
。 / p>
可能的问题是flow
在switch
内部如何工作。
关于如何进行这项工作的任何想法?
谢谢!
答案 0 :(得分:0)
此错误的主要原因是当前操作类型注释太宽(string
)。解决方案是使它们更窄。要进行这项工作,需要进行一些更改。
1)在actions
中的操作类型中添加狭窄的注释。假设actions
当前看起来像:
// @flow
export const LOAD_INDEX = 'LOAD_INDEX';
export const LOAD_ALL = 'LOAD_ALL';
export const DELETE_ALL = 'DELETE_ALL';
应更改为
export const LOAD_INDEX: 'LOAD_INDEX' = 'LOAD_INDEX';
export const LOAD_ALL: 'LOAD_ALL' = 'LOAD_ALL';
export const DELETE_ALL: 'DELETE_ALL' = 'DELETE_ALL';
2)在types.js
中为操作类型添加更窄的注释。
src \ types.js
import { LOAD_INDEX, LOAD_ALL, DELETE_ALL } from './actions';
export type TLoadIndex = { type: typeof LOAD_INDEX, index: number }
export type TLoadAll = { type: typeof LOAD_ALL}
export type TDeleteAll = { type: typeof DELETE_ALL}
export type TAction = TLoadIndex | TLoadAll | TDeleteAll;
export type TPlane = {
title?: string,
caption?: string,
text?: string,
image: string,
};