【问题标题】:Flow-type Union-type for Module exportsFlow-type Union-type 用于模块导出
【发布时间】:2017-08-23 20:37:55
【问题描述】:

模块导出是否有联合类型格式...例如:

// actionTypes.js
export const CREATE_ACCOUNT = 'CREATE_ACCOUNT'
export const UPDATE_ACCOUNT = 'UPDATE_ACCOUNT'
export const DELETE_ACCOUNT = 'DELETE_ACCOUNT'

// reducer.js
import * as actionTypes from './actionTypes.js'

type Action = actionTypes
export default function( state: Object, action: Action){ ... }

【问题讨论】:

  • 在导入文件中有需要这样做的理由吗?我通常只是在将动作类型定义为的模块中创建联合类型:`export type ActionTypes = 'blah' | 'foo'``。
  • 我已经在 actionTypes.js 文件中有字符串,所以我想我可以在 FTW 中重复使用它。

标签: javascript module ecmascript-6 flowtype es6-modules


【解决方案1】:

您可以使用 $Values 将对象的值转换为 Union 类型。但是请注意,将字符串分配给 const 仍然将该值键入为string。您将需要显式键入每个变量,或使用 $ObjMap 之类的内容。

一个例子可能是这样的:

// actionTypes.js
export const CREATE_ACCOUNT: 'CREATE_ACCOUNT' = 'CREATE_ACCOUNT'
export const UPDATE_ACCOUNT: 'UPDATE_ACCOUNT' = 'UPDATE_ACCOUNT'
export const DELETE_ACCOUNT: 'DELETE_ACCOUNT' = 'DELETE_ACCOUNT'

// reducer.js
import * as actionTypes from './actionTypes.js'

type Action = $Values<typeof actionTypes>;
export default function( state: Object, action: Action){ ... }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-15
    • 1970-01-01
    • 1970-01-01
    • 2016-07-20
    • 2014-08-05
    • 2020-04-30
    • 1970-01-01
    • 2022-12-09
    相关资源
    最近更新 更多