I want to have a nested array of Items
type Item = { name: string }
I've come across a few approaches and I'm trying the differences in them.
Using
typetype Item = { name: string } type NestedArray<T> = Array<T> | Array<NestedArray<T>>; type Items = NestedArray<Item>;But with this approach it seems I can't have
Itemsand a nested array ofItemsin the same array:const items: Items = [ // item, Error: Type '(Item | Item[][])[]' is not assignable to type 'Items'. [ // item, Error: Type 'Item' is not assignable to type 'NestedArray<Item>' [ // item, Error: Type '[Item, [any]]' is not assignable to type 'NestedArray<Item>' [ item, // Works only as long as there isn't a nested array alongside item ] ] ] ]But at least it has normal Array functions:
items.map(i => i) // worksUsing
interfaceinterface Items { [n: number]: Item | Items }const items: Items = [ item [ item [ item [ item, // All Works! ] ] ] ]But
interface Itemsis no longer anArray(that hasmapetc functions)items.map(i => i) // Error: Property 'map' does not exist on type 'Items'.
How to get the best of both worlds?
- A deeply nested array that allows items and array of items side-by-side.
- Implements normal Array functions like map/filter etc.
const items: Items[][][] = [[[{name:"blah"}]]];One of the advantages of type annotations is to prevent excessive runtime type-checking, so it makes sense to declare things this way.