我想有一个嵌套的Item
数组
type Item = { name: string }
我遇到了一些方法,我正在尝试它们之间的差异。
使用
type
type Item = { name: string } type NestedArray<T> = Array<T> | Array<NestedArray<T>>; type Items = NestedArray<Item>;
但是用这种方法,似乎我不能有
Items
和Items
嵌套数组在同一个数组: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 ] ] ] ]
但至少它有正常的数组函数:
items.map(i => i) // works
使用
interface
interface Items { [n: number]: Item | Items }
const items: Items = [ item [ item [ item [ item, // All Works! ] ] ] ]
interface Items
不再是Array
(具有map
等功能)items.map(i => i) // Error: Property 'map' does not exist on type 'Items'.
如何做到两全其美?
- 一个深度嵌套的数组,允许项目和项目数组并排。
- 实现普通数组函数,如map/filter等
但是用这种方法,似乎我不能在同一个数组中有项目和嵌套的项目数组
应该建议需要的更改:
type NestedArray<T> = Array<T | NestedArray<T>>;
。而不是"一个T
的数组或一个NestedArray<T>
的数组";创建一个包含(T
或NestedArray<T>
)的数组。
用Array
扩展Items
接口:
type Item = { name: string }
interface Items extends Array<Item | Items> { [n: number]: Item | Items }
const item = { name: 'John' }
const items: Items = [item, [item, [item, [item,],]]]
items.map(e => e) // ok
const x = items[0] // Item | Items
游乐场