【问题标题】:Testing type of union variable without verifying properties在不验证属性的情况下测试联合变量的类型
【发布时间】:2020-12-14 04:27:25
【问题描述】:

我正在尝试检查联合类型变量的值的类型。

/* @flow */

type A = {
  a: number, 
  b: number
}

type B = {
  c: string
}

const fun1: (A | B) => void = (x) => {
  if (x.a) {
    x.a
    x.b // Doesn't work
  }
  if (x.b) {
    x.b
    x.a // Doesn't work
  }
  if (x.c) {
    x.c
  }
}

检查单个属性是唯一的方法吗?在上面的例子中,我们知道如果x.a,那么也是x.b。有没有办法检查A 类型或B 类型所以我可以写

const fun1: (A | B) => void = (x) => {
  if (typeof x === 'A') { // Cannot compare the result of `typeof` to string literal `A` because it is not a valid `typeof` return value.
    x.a // Works
    x.b // Works
  }
}

【问题讨论】:

    标签: functional-programming flowtype


    【解决方案1】:

    您的代码失败了,因为默认情况下 Flow 对象类型允许未指定的属性,因此例如以下是可以的:

    let a: A = {
      a: 1,
      b: 2,
      c: "",
    };
    

    所以A 类型很可能符合B 类型,与您当前的定义。

    为避免这种情况,您需要将AB 设为exact object types,因此Flow 知道它们不允许额外的随机属性。例如

    type A = {|
      a: number, 
      b: number
    |}
    
    type B = {|
      c: string
    |}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-04
      • 1970-01-01
      • 2021-10-06
      • 2016-06-24
      • 1970-01-01
      • 1970-01-01
      • 2020-05-20
      相关资源
      最近更新 更多