【问题标题】:Flowtype - generic arrayFlowtype - 泛型数组
【发布时间】: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&lt;?Object&gt; 适合你,为什么你不喜欢它?
  • 因为当我把 Array 放在那里时,它返回 Array。所以我丢失了信息,数组中有 Persons。
  • @FrantišekBelšán 这个怎么样:flow.org/try/…
  • @MarkoSavic 感谢您的回答,但我需要一些不同的东西。看问题,我添加了“Flow try”链接。

标签: flowtype


【解决方案1】:

由于 flow 存在 Refine array types using filter 的错误,我们使用显式类型转换 ((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]);

【讨论】:

  • 我使问题描述更好,因为我认为我们不在同一页。你现在明白我了吗?
【解决方案2】:

我找到了:)

export function trimList<V>(list: Array<?V> | $ReadOnlyArray<?V>): Array<V> {
  return R.filter(isNotUndefinedOrNull, list);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-16
    • 2017-12-02
    • 2020-05-02
    • 1970-01-01
    • 2019-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多