类型vs嵌套数组的接口-使用哪个?



我想有一个嵌套的Item数组

type Item = { name: string }

我遇到了一些方法,我正在尝试它们之间的差异。

  1. 使用type

    type Item = { name: string }
    type NestedArray<T> = Array<T> | Array<NestedArray<T>>;
    type Items = NestedArray<Item>;
    

    但是用这种方法,似乎我不能有ItemsItems嵌套数组在同一个数组:

    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
    
  2. 使用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>的数组";创建一个包含(TNestedArray<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 

游乐场

最新更新