我如何编写泛型函数,它接受对象数组(任何类型的对象,甚至可能是空的和未定义的),并过滤它以返回数组的有效项?如果我把它写成这样,我就失去了普遍性。
// @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);问题是,我已经修剪了汽车和人员,但是flow不知道,在trimmedCars列表中有汽车,也不知道trimmedPersons列表中有人员。流看到只是阵列,我不知道,如何写是正确的,不要失去这个信息。流试
发布于 2018-11-21 07:56:50
我找到了)
export function trimList<V>(list: Array<?V> | $ReadOnlyArray<?V>): Array<V> {
return R.filter(isNotUndefinedOrNull, list);
}发布于 2018-10-18 16:46:37
由于flow在使用筛选器细化数组类型中有一个bug,所以我们使用显式类型的((res): any): T[])。
function filterNullable<T>(items: (?T)[]): T[] {
const res = items.filter(item => !(item === null || item === undefined);
return ((res): any): T[]);
}
// Example
const a: number[] = filterNullable([1, 2, null, undefined]);https://stackoverflow.com/questions/52850958
复制相似问题