是否可以从应用程序代码中的 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 (className
、id
等)。
可以从类似于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/