首页 > 解决方案 > 用于嵌套对象数组的 Typescript 接口

问题描述

我是 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,
}

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

标签: javascriptreactjstypescriptreact-typescript

解决方案


你可以这样试试

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

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

另请注意,数据接口不应以命名约定开头 具有方法声明的 "I"接口应具有"I"IMethodService


推荐阅读