首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Flowtype -泛型数组

Flowtype -泛型数组
EN

Stack Overflow用户
提问于 2018-10-17 08:57:07
回答 2查看 593关注 0票数 1

我如何编写泛型函数,它接受对象数组(任何类型的对象,甚至可能是空的和未定义的),并过滤它以返回数组的有效项?如果我把它写成这样,我就失去了普遍性。

代码语言:javascript
复制
// @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列表中有人员。流看到只是阵列,我不知道,如何写是正确的,不要失去这个信息。流试

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-11-21 07:56:50

我找到了)

代码语言:javascript
复制
export function trimList<V>(list: Array<?V> | $ReadOnlyArray<?V>): Array<V> {
  return R.filter(isNotUndefinedOrNull, list);
}
票数 0
EN

Stack Overflow用户

发布于 2018-10-18 16:46:37

由于flow在使用筛选器细化数组类型中有一个bug,所以我们使用显式类型的((res): any): T[])

代码语言:javascript
复制
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]);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52850958

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档