【发布时间】:2019-03-21 21:38:14
【问题描述】:
我如何编写通用函数,该函数采用对象数组(任何类型的对象,甚至可能为 null 和未定义),并对其进行过滤以仅返回有效的数组项?如果我把它写成精简版,我将失去通用性:/
// @flow
// Types
type Person = {
id: string,
name: string,
};
type Car = {
id: string,
color: string,
};
// Function definition
const isNotUndefinedOrNull = item => !(item === null || item === undefined);
export const trimList = (list: Array<any> | $ReadOnlyArray<any>): Array<any> => {
return list.filter(isNotUndefinedOrNull);
};
// Constants
const persons = [{ id: 'p1', name: 'Johny' }, null, undefined];
const cars = [{ id: 'c1', color: 'red' }, null, undefined];
// Calls
const trimmedPersons = trimList(persons);
const trimmedCars = trimList(cars);
问题是,我已经修剪了汽车和人员,但流程不知道,在 trimmedCars 列表中有汽车,也不知道在 trimmedPersons 列表中有人员。 Flow 只看到 Array 而我不知道,如何编写是正确的,以免丢失此信息。 Flow try
【问题讨论】:
-
Array<?Object>适合你,为什么你不喜欢它? -
因为当我把 Array 放在那里时,它返回 Array
-
@FrantišekBelšán 这个怎么样:flow.org/try/…
-
@MarkoSavic 感谢您的回答,但我需要一些不同的东西。看问题,我添加了“Flow try”链接。
标签: flowtype