在访问可为 nullable 属性 之前过滤掉可能的类型

Filtering out maybe types before accessing nullable property

给定这两种类型:

type Point = [
  number,
  number,
];

type Some = {
  a: Point,
  b: ?Point,
};

和数据集:

const somes: Array<Some> = [
  {a: [0, 1], b: [0, 2]}, 
  {a: [2, 3], b: null}
]

如果我们尝试访问 somes[n].b.x,假设 b 是一个 maybe 类型并且可能为 null 或 undefined,Flow 将自动失败。

但是,我们可以自信地过滤掉 somes 中的所有项目,以排除任何不包含 b:

的项目
const withB = somes.filter(s => !!s.b)

然而,flowtype 在访问 withB 中的项目时仍然会抱怨,因为它没有选择排除项:

console.log( withB.map(s => s.b[0]).join(',') )
// console.log(withB.map(s => s.b[0]).join(','))
//                              ^^^^^^ access of computed property/element. // Computed property/element cannot be accessed on possibly undefined value
// console.log(withB.map(s => s.b[0]).join(','))
//                            ^^^ undefined

是否有可能以某种方式注释或提示 withB 中的所有项目现在保证包含 b 属性?

以下是提示 Flow anything 的一般方法:

 const withB: Array<{ a: Point, b: Point }> = (somes.filter(s => !!s.b): any)

不过你的情况不安全。您有一个可变对象数组,属性 'b' 可以随时设置为 null

如果您愿意为额外的计算付费,另一种选择

const withB = somes
  .map(x => x.b ? { a: x.a, b: x.b } : null)
  .filter(Boolean)