recursion - How can I infer a recursive TypeScript Type? -
i building typescript collection class application have struggled find solution in order infer recursive calls.
arrays.ts
export interface arrayable<t> { toarray(): array<t>; } export function isarrayable<t>(object: any): object arrayable<t> { return typeof object === "object" && 'toarray' in object; }
collection.ts
import { arrayable, isarrayable } "./arrays"; export class collection<t> implements arrayable<t> { private elements: array<t>; constructor(elements?: array<t> | arrayable<t>) { if (typeof elements === "undefined") return; this.elements = this.getelementsarray(elements); } chunk(size: number): collection<collection<t>> { let chunked = []; (let = 0, len = this.elements.length; < len; += size) chunked.push(new collection(this.elements.slice(i, + size))); return new collection(chunked); } toarray(): any[] { return this.elements.map((value: t) => { if (isarrayable(value)) return value.toarray(); return value; }); } private getelementsarray(elements: array<t> | arrayable<t>): array<t> { if (array.isarray(elements)) { return elements; } else if (isarrayable(elements)) { return elements.toarray(); } } }
app.ts
let col = new collection([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) .chunk(3) .toarray();
here value of col typed any[] current work around.
is there way infer number[][]? want toarray recursively collapse collection required.
Comments
Post a Comment