简体   繁体   中英

Typescript interface for a nested array of objects

I'm new to Typescript and I have to build an interface for the following props type:

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: '#' }]
  }
];

I want to create an interface for it to be used in a React + Typescript app.

This is the interface so far:

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

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

It is not working, it should have some arrays I guess. Any suggestions?

You can try like this,

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM