简体   繁体   English

嵌套对象数组的打字稿接口

[英]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:我是 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: '#' }]
  }
];

I want to create an interface for it to be used in a React + Typescript app.我想为它创建一个接口以在 React + Typescript 应用程序中使用。

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另请注意,数据接口不应以命名约定"I"开头具有方法声明的接口应具有"I"IMethodService

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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