精炼混合到Flow中的已知对象类型

Dan*_*Dan 1 javascript flowtype

我们正在尝试在Flow中进行类型细化,以防止在外部接口上进入应用程序的值.要做到这一点,我们正在使用mixed然后尝试改进已知类型,但Flow并不容易!

以下似乎应该可以工作,我已经验证了mixed类型值与类型的要求相匹配response.

type Response = { head: string }

const refineToResponse = (value: mixed): ?Response => {   
  if (value
    && typeof value === "object"
    && typeof value.head === "string") {

    return value;   
  }

  return null; 
};
Run Code Online (Sandbox Code Playgroud)

但我只是得到一个非常无益的错误消息:

16:     return value;
               ^^^^^ object. This type is incompatible with the expected return type of
11: const refineToResponse = (value: mixed): ?Response => {
                                              ^^^^^^^^ object type   
Run Code Online (Sandbox Code Playgroud)

属性head不兼容:

 11: const refineToResponse = (value: mixed): ?Response => {
                                                 ^^^^^ mixed. This type is incompatible with
  8:   head: string
             ^^^^^^ string
Run Code Online (Sandbox Code Playgroud)

编辑:

TryFlow上代码的链接.

vku*_*kin 5

这将是不安全的.如果某些东西string在运行时有类型,那并不意味着它具有相同的静态类型,例如它可能是一些枚举:'Foo' | 'Bar',所以使它只是string允许不安全的突变.另一方面,它可能是number | string,所以在未来head可能真的成为一个数字或任何类型.

相反,您可以执行以下操作:

const refineToResponse = (value: mixed): ?Response => {   
  if (value
    && typeof value === "object"
    && typeof value.head === "string") {

    return { head: value.head };   
  }

  return null; 
};
Run Code Online (Sandbox Code Playgroud)