1

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.

2
  • The second code is for inside of a react component -- is that what you are doing or do you just need simple help with an array in a non-react program? Commented Dec 22, 2022 at 11:05
  • Also keep in mind that return value of the push method is not the mutated source but only resulting length of the mutated source. Commented Dec 22, 2022 at 11:15

2 Answers 2

5

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 } ]);
}

Sign up to request clarification or add additional context in comments.

Comments

0

Add the type to the ‍‍useState:

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

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.