在Flow中将混合细化为已知的对象类型 [英] Refining mixed to a known object type in Flow
问题描述
我们正在尝试在Flow中进行类型优化,以防止值在外部接口进入我们的应用程序.为此,我们使用 mixed
,然后尝试优化为已知类型,但是Flow并不容易!
We're trying to do type refinement in Flow to guard against values entering our application at the external interfaces. To do this we're using mixed
and then trying to refine to known types, but Flow isn't make it easy!
以下似乎应该可行,我已经验证了 mixed
类型的值是否符合 response
类型的要求.
The following seems like it should work, I've validated that the mixed
type value matches the requirements of the response
type.
type Response = { head: string }
const refineToResponse = (value: mixed): ?Response => {
if (value
&& typeof value === "object"
&& typeof value.head === "string") {
return value;
}
return null;
};
但是我只是收到一条非常无用的错误消息:
But I just get a very unhelpful error message:
16: return value;
^^^^^ object. This type is incompatible with the expected return type of
11: const refineToResponse = (value: mixed): ?Response => {
^^^^^^^^ object type
属性 head
不兼容:
11: const refineToResponse = (value: mixed): ?Response => {
^^^^^ mixed. This type is incompatible with
8: head: string
^^^^^^ string
推荐答案
那是不安全的.如果某项在运行时具有 string
类型,则并不意味着它具有相同的静态类型,例如可能是一些枚举:'Foo'|'Bar'
,因此将其设置为 string
可能会导致不安全的突变.另一方面,它可能是 number |字符串
,所以将来 head
可能会变成数字或任何类型.
That would be unsafe. If something has type string
at runtime, it doesn't mean that it has the same static type, e.g. it could be some enum: 'Foo' | 'Bar'
, so making it just string
would allow unsafe mutations. On the other hand, it could be number | string
, so in the future head
could become a number or any type, really.
相反,您可以执行以下操作:
Instead you can do the following:
const refineToResponse = (value: mixed): ?Response => {
if (value
&& typeof value === "object"
&& typeof value.head === "string") {
return { head: value.head };
}
return null;
};
这篇关于在Flow中将混合细化为已知的对象类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!