用于嵌套对象数组的 Typescript 接口

Typescript interface for a nested array of objects

我是 Typescript 的新手,我必须为以下道具类型构建一个界面:

const myProps = [
  {
    name: 'name1',
    on: true,
    children: [
      { name: 'test1', href: '#' },
      { name: 'test2', href: '#' },
      { name: 'test3', href: '#' }
    ]
  },
  {
    name: 'name2',
    on: false,
    children: [
      { name: 'test1', href: '#' },
      { name: 'test2', href: '#' },
      { name: 'test3', href: '#' },
      { name: 'test4', href: '#' },
      { name: 'test5', href: '#' }
    ]
  },
  {
    name: 'name3',
    on: false,
    children: [{ name: 'test1', href: '#' }]
  }
];

我想为它创建一个界面,以便在 React + Typescript 应用程序中使用。

这是目前的界面:

export interface IChildren {
  name: string,
  href: string
}

export interface IMyProps {
  name: string,
  on: boolean,
  children: IChildren,
}

它不起作用,我猜它应该有一些数组。有什么建议吗?

你可以这样试试,

 export interface CommonProps {
    name: string;
    href: string;
}

export interface MyProps {
    name: string;
    on: boolean;
    children: Array<CommonProps>;
}

Also Note data interfaces should not start with naming conventions "I" Interfaces those have method declarations should have "I" like IMethodService

如果您使用两个接口,您可以使用以下两种方法。

  export interface ChildrenProp {
        name: string,
        href: string
    }

  export interface MyProps {
        name: string;
        on: boolean;
        children: ChildrenProp[]
    }

    export interface MyProps {
        name: string;
        on: boolean;
        children: Array<ChildrenProp>
    }

如果你不使用两个接口可以使用下面的方法

export interface MyProps {
    name: string;
    on: boolean;
    children: {
       name: string,
       href: string
    }[]
}