我正在使用flow用于使用redux在React应用中输入type type,并且需要在还原类型中检查速度的动作形状,如下所述:https://flow.org/en/doc/react/redux/
还原代码:
import { ADD_USER, DELETE_USER } from './actionTypes'
type State = {
users: { [userId: number]: { name: string, age: number } }
}; // exact State shape is not important for this case
type Action =
|{ type: ADD_USER, user: {name: string, age: number} }
|{ type: DELETE_USER, userId: number };
function reducer(state: State, action: Action): State {
switch(action.type) {
case ADD_USER:
return { ...state, users: { ...state.users, action.user } };
case DELETE_USER:
const { action.userId, ...newUsers } = state.users
return { ...state, users: newUsers };
default:
return state;
}
这不起作用,给出流动错误 Cannot get 'action.userId' because property 'userId' is missing in object type
。
当我将操作类型定义为同一文件中的常数时,类型检查工作有效:
// import { ADD_USER, DELETE_USER } from './actionTypes'
const ADD_USER = 'ADD_USER';
const DELETE_USER = 'DELETE_USER';
type State = {
users: { [userId: number]: { name: string, age: number } }
}; // exact State shape is not important for this case
type Action =
|{ type: ADD_USER, user: {name: string, age: number} }
|{ type: DELETE_USER, userId: number };
function reducer(state: State, action: Action): State {
switch(action.type) {
case ADD_USER:
return { ...state, users: { ...state.users, action.user } };
case DELETE_USER:
const { action.userId, ...newUsers } = state.users
return { ...state, users: newUsers };
default:
return state;
}
需要将操作类型名称作为字符串常数导入,因为它们也是在动作创建者中导入的,因此可以将它们全部定义在一个文件actionTypes.js
中(用React-Redux的标准方法)。
如何使用导入常数进行流动类型检查?
我认为需要做一些事情。
1)将类型添加到actionTypes.js
中的操作类型。确保该操作类型在那里分配如下:
const ADD_USER: 'ADD_USER' = 'ADD_USER';
const DELETE_USER: 'DELETE_USER' = 'DELETE_USER';
2)在"缩减代码"中的"动作类型"注释中,请确保使用类型而不是操作值的值,如下所示:
import { ADD_USER, DELETE_USER } from './actionTypes'
type Action =
|{ type: typeof ADD_USER, user: {name: string, age: number} }
|{ type: typeof DELETE_USER, userId: number };
3)确保所有其他代码都是有效的JavaScript,因为users: { ...state.users, action.user }
和{ action.userId, ...newUsers } = state.users
看起来不像是进行新对象的破坏和创建的合法方法。