我一直在尝试将一个功能性React组件从PropTypes转换为Flow。为该组件提供了一个对象,该对象包含要在组件中使用的字符串。
以前它看起来像这样:
Component.propTypes = {
strings: PropTypes.objectOf(PropTypes.string),
}
Component.defaultProps = {
strings: {
key_one: "string one",
key_two: "string two",
}
}
我已将其转换为:
type Props = {
strings?: { [string_key: string]: string },
}
const Component = ({ strings }: Props) => (
// component using
// label={strings.key_one}
// etc
)
Component.defaultProps = {
strings: {
key_one: "string one",
key_two: "string two",
}
}
这会产生错误:
Cannot get strings.key_one because property key_one is missing in undefined [1].
[1] strings?: { [string_key: string]: string },
如果我删除[string_key: string]: ?string
,除了第一条错误消息之外,还会产生第二条错误消息:
property key_one is missing in object type [1].
如果我删除了可选标记,那么错误就会消失,但我无法提供默认道具(strings?: { [string_key: string]: string },
->strings: { [string_key: string]: string },
(。
阅读问题似乎是由于在从JSX转换过程中发生的精化无效,这里注意到:https://github.com/facebook/flow/issues/6350.
有人能透露更多的信息吗,知道是否有办法解决这个问题吗?
我相信我已经找到了自己问题的答案。这是不直观的。
查看线程https://github.com/facebook/flow/issues/1660.
它看起来像:
您不需要制作。。。道具。。。在道具类型中是可选的。Flow will如果您有foo的默认道具,请确保foo是可选的。
测试我现有的测试似乎确实通过了——这表明即使没有用?
标记,指定的默认道具仍然会在快照中捕获。这是有效的,但确实减少了type Props =
作为文档本身的使用。