如何在打字稿中实现嵌套数组

时间:2018-10-21 19:22:52

标签: typescript

我不明白如何在打字稿中定义一些变量:

interface ItemType {
    name: string;
    val: string;
    id: number;
}

const items: ItemType[] | ItemType[][] = [
    { name: 'russia', val: 'ru', id: 1 },
    { name: 'england', val: 'en', id: 2 },
    { name: 'america', val: 'us', id: 3 },
    { name: 'canada', val: 'ca', id: 4 },
    { name: 'ukraine', val: 'uc', id: 5 },
    [
        { name: 'havana', val: 'hv', id: 6 },
        { name: 'argentina', val: 'ar', id: 7 },
        { name: 'kazahstan', val: 'kz', id: 8 },
    ]
];

根据设计,项目可以是ItemType的数组,但是在某些情况下,这里可以是ItemType的另一个嵌套数组,而我不明白,我怎么能这样声明变量? This code obviously wrong :( 我认为我必须使用通用类型

谢谢。

1 个答案:

答案 0 :(得分:0)

这些声明应该执行:

const items: (ItemType | ItemType[])[] = [
  {name: 'russia', val: 'ru', id: 1},
  {name: 'england', val: 'en', id: 2},
  {name: 'america', val: 'us', id: 3},
  {name: 'canada', val: 'ca', id: 4},
  {name: 'ukraine', val: 'uc', id: 5},
  [
    {name: 'havana', val: 'hv', id: 6},
    {name: 'argentina', val: 'ar', id: 7},
    {name: 'kazahstan', val: 'kz', id: 8},
  ]
];

或:

const items: Array<ItemType | ItemType[]> = [
  {name: 'russia', val: 'ru', id: 1},
  {name: 'england', val: 'en', id: 2},
  {name: 'america', val: 'us', id: 3},
  {name: 'canada', val: 'ca', id: 4},
  {name: 'ukraine', val: 'uc', id: 5},
  [
    {name: 'havana', val: 'hv', id: 6},
    {name: 'argentina', val: 'ar', id: 7},
    {name: 'kazahstan', val: 'kz', id: 8},
  ]
];