Home > Blockchain >  How to add a type for array of objects using react and typescript?
How to add a type for array of objects using react and typescript?

Time:01-03

i have to provide type for array of objects using react and typescript?

below is the code,

const SomeComponent = (item: string, children: any) => {
    //some logic
}

here as you see for children i have use any type instead i want to use type of its own. when i log children in console its like below an array of objects

[
    {
        id: '1',
        children: [],
    },
    {
        id: '2',
        children: [
            { 
                id: '21',
                name: 'children1',
            },
        ],
    },
]

What should be the type of children instead of any. i am new to using typescript. could someone help me with this. thanks.

CodePudding user response:

If you have defined class or interface Child, you can use

children: Child[]

In general, array of object is noted as object[]

CodePudding user response:

Assuming that children and top level array is not recursive data structure you can use this type:



type Item = {
    id: `${number}`;
    children: Child[]
}

type Child = {
    id: `${number}`;
    name: `children${number}`;
}

const arr: Item[] = [
    {
        id: '1',
        children: [],
    },
    {
        id: '2',
        children: [
            {
                id: '21',
                name: 'children1',
            },
        ],
    },
]

This syntax/type - `${number}` means that it is a string but contains only numbers

  • Related