javascript - 从代码中的 Flow 对象类型获取键

标签 javascript reactjs webpack flowtype

是否可以从应用程序代码中的 Flow 对象类型定义获取 key (换句话说,Flow 类型定义是否以任何方式在运行时代码中具体化)?

用例:

type Props = {
  userID: string,
  size: number | PhotoSize,
  subscribePresence: Function,
  unsubscribePresence: Function,
  presenceStatus: ?PresenceStatus,
  photoURL: ?string,
  userName: ?string,
};

class Photo extends Component<Props> {
  // ...
  render() {
    const { userID, size, presenceStatus } = this.props;
    // Other props used elsewhere in the component
    const restProps = _.omit(this.props, ???)
  }
}

扩展解构(const {/* etc */...rest} = this.props)不起作用,因为还有其他 Prop 在 中不使用渲染。但是,我想选取可能已指定的其他 Prop (classNameid 等)。

可以从类似于Object.keys(Props)的东西派生出???吗?据我所知,类型定义已被编译掉,因此尝试在运行时代码中引用Props会抛出RuntimeError:Props未定义

最佳答案

Flow 提供静态类型分析,并且所有 Flow 代码在运行前都会被剥离(流注释不是有效的 Javascript 代码)。

为了实现您想要的目标,您需要在剥离 Flow 代码后获得有关预期 Props 的信息。您可以通过设置 defaultProps 来做到这一点对于组件中的所有 Prop ,然后您可以编写:

const restProps = _.omit(this.props, Photo.defaultProps)

无论如何,设置 defaultProps 通常是个好主意。

关于javascript - 从代码中的 Flow 对象类型获取键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47656749/

相关文章:

javascript - 如何将隐藏变量添加到输入字段

javascript - 堆的算法返回数组而不是打印

javascript - React Checkbox Group/Individual 复选框

reactjs - React TypeScript 类型提示自动完成不适用于 Visual Studio Code 中的 React.forwardRef

javascript - window.location.href 与 $ (".confirm").click(function (e) 不返回完整网址

javascript - 在 JavaScript 中将字符串与 null 或空值进行比较

npm - 将应用程序安装为 npm 包后,找不到 “vue-cli-service”

javascript - 将 HTTP Basic Auth 添加到 Webpack Dev Server

javascript - React OIDC-Client IE Promise 未定义

angularjs - webpack 和 less 如何在 css 中包含图像 url