I am trying to write in typescript something similar to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat
However, I want to be able to flatten nested list of arbitrary depth; and also I want to restrict all non array elements to a single type.
Something like:
interface NestedList<T> extends Array<T | NestedList<T>> {}
I have got this so far:
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, []);
};
However, the type inference does not seem to be working
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 }]);
});
It receives type error on this line:
const list2: Foo<number>[] = flat(nested);
Error:
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>'
What I am missing here? Any help is appreciated.
I stumbled on the same problem as you. This is the solution I came up with:
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])
Hope it helps you :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.