Home > Enterprise >  How do I create dynamic array in typescript?
How do I create dynamic array in typescript?

Time:12-22

I want to create a dynamic array in typescript in the following format

const display = [
    { id: 1, displayName: "Abc1" },
    { id: 2, displayName: "Abc2" },
    { id: 3, displayName: "Abc3" }
]

I have tried the following codes

const [display, SetDisplay] = useState([])

function createData(id: number, name: string) {
    return { id, name };
}

SetDisplay(display.push(createData(1, "Abc1")))

But can not push data into the variable display. Getting error like

Argument of type '{ id: number; result: string; }' is not assignable to parameter of type 'never'.

Any information for resolving this would be helpful.

CodePudding user response:

You should not mutate the state directly.

You can directly do a setState and destructure your previous array to add new data.

You can as well type your setState as follow <{id: number; name:string}>

const [display,setDisplay] = useState<{id: number; name:string}>([]);

function createData(id: number, name: string) {
  setDisplay((prev) => [...prev, { id, name } ]);
}

CodePudding user response:

Add the type to the ‍‍useState:

const [display,SetDisplay] = 
  useState<{id: number,name: string}[]>([]);
  • Related