【问题标题】:Typescript interface for a nested array of objects用于嵌套对象数组的 Typescript 接口
【发布时间】:2021-11-11 09:11:19
【问题描述】:

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

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

【问题讨论】:

  • IMyPropschildren 属性的类型应该是一个数组,Array<IChildren>IChildren[]
  • @Wazeed 你为什么不把你的评论变成答案。

标签: javascript reactjs typescript react-typescript


【解决方案1】:

你可以这样试试,

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

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

还要注意数据接口不应该以命名约定开头 "I" 那些有方法声明的接口应该有 "I"IMethodService

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-02
    • 2019-11-23
    • 2019-10-28
    • 2018-11-05
    • 2020-05-02
    • 1970-01-01
    相关资源
    最近更新 更多