3

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?

2
  • 3
    Type of children property in IMyProps should be an array, either Array<IChildren> or IChildren[] Commented Nov 11, 2021 at 9:13
  • @Wazeed why don't you convert your comment into an answer. Commented Nov 11, 2021 at 9:15

2 Answers 2

3

If you are using two interfaces you can use the following two methods.

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

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

or

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

If you are not using two interfaces you can use the following method

export interface MyProps {
    name: string;
    on: boolean;
    children: {
       name: string,
       href: string
    }[]
}
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.