我正在使用Flow在使用Redux的React应用程序中进行类型检查,并且需要根据操作类型检查减速器中的操作形状,如此处所述:https://flow.org/en/docs/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的标准方法)。
如何使用导入的常数执行不连续联合的流类型检查?
答案 0 :(得分:1)
我认为需要做一些事情。
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
看起来不是进行解构和创建新对象的合法方法。