如何为数组编写类型化展平方法

问题描述 投票:0回答:1

我正在尝试用 TypeScript 编写类似于 Array.prototype.flat().

的内容

但是,我希望能够展平任意深度的嵌套列表;而且我想将所有非数组元素限制为单一类型。

类似:

interface NestedList<T> extends Array<T | NestedList<T>> {}

到目前为止我已经得到了这个:

export const flat = <T>(ls: NestedList<T>): T[] => {
   const reducer = (acc: T[], it: T | NestedList<T>): T[] => acc.concat(
      Array.isArray(it) ? it.reduce(reducer, []) : it
   );

   return ls.reduce(reducer, []);
};

但是,类型推断似乎不起作用:

   it('works with type inference', () => {
      interface Foo<T> { v: T; }

      const data: { [_: string]: { [_: string]: Foo<number> } } = {
         bar: { x: { v: 1 } },
         moo: { y: { v: 2 }, z: { v: 3 } }
      };

      const nested: Foo<number>[][] = Object.values(data).map(val => Object.values(val));
      const list2: Foo<number>[] = flat(nested);
      expect(list2).toEqual([{ v: 1 }, { v: 2 }, { v: 3 }]);
   });

它在此行收到类型错误:

const list2: Foo<number>[] = flat(nested);

错误:

Type '(Foo<number>[] | ConcatArray<Foo<number>[]>)[]' is not assignable to type 'Foo<number>[]'.
  Type 'Foo<number>[] | ConcatArray<Foo<number>[]>' is not assignable to type 'Foo<number>'.
    Property 'v' is missing in type 'Foo<number>[]' but required in type 'Foo<number>'

我在这里缺少什么?

typescript type-inference type-systems
1个回答
0
投票

我偶然发现了和你一样的问题。这是我想出的解决方案:

function flat<U>(arr: U[][]): U[] {
    if ((arr as unknown as U[]).every((val) => !Array.isArray(val))) {
        return (arr as unknown as U[]).slice();
    }
    return arr
        .reduce((acc, val) => acc
            .concat(Array.isArray(val) ? flat((val as unknown as U[][])) : val), []);
}

console.log(flat([[1,2],[[[3]]],4])
© www.soinside.com 2019 - 2024. All rights reserved.