Since the object you want to add has a nested property action, you might want to use destructuring to get just the action key as your inserItem function's argument.

const insertItem = (array, { action }) => [
   ...array.slice(0, action.index),
   action.item,
   ...array.slice(action.index),
];

const ori_arr = [{
  id: 1,
  name: 'james',
  age: 10
}, {
  id: 2,
  name: 'terrance',
  age: 20
}]

console.log(insertItem(ori_arr, {
  action: {
    index: 1,
    item: {
       id: 3,
       name: 'she',
       age: 44
    }
  }
}))

Hovever, if you'd prefer to avoid destructuring, just change the name of your second argument in the insertItem function for e.g. obj and then just add obj before every action.index in your function:

const insertItem = (array, obj) => [
   ...array.slice(0, obj.action.index),
   obj.action.item,
   ...array.slice(obj.action.index),
];
Answer from kind user on Stack Overflow
Top answer
1 of 2
2

Since the object you want to add has a nested property action, you might want to use destructuring to get just the action key as your inserItem function's argument.

const insertItem = (array, { action }) => [
   ...array.slice(0, action.index),
   action.item,
   ...array.slice(action.index),
];

const ori_arr = [{
  id: 1,
  name: 'james',
  age: 10
}, {
  id: 2,
  name: 'terrance',
  age: 20
}]

console.log(insertItem(ori_arr, {
  action: {
    index: 1,
    item: {
       id: 3,
       name: 'she',
       age: 44
    }
  }
}))

Hovever, if you'd prefer to avoid destructuring, just change the name of your second argument in the insertItem function for e.g. obj and then just add obj before every action.index in your function:

const insertItem = (array, obj) => [
   ...array.slice(0, obj.action.index),
   obj.action.item,
   ...array.slice(obj.action.index),
];
2 of 2
0

You're passing the parameters incorrectly:

console.log(insertItem(ori_arr, {
  action: {
    index: 1,
    item: {
       id: 3,
       name: 'she',
       age: 44
    }
  }
}))

instead pass it without the action object:

console.log(insertItem(ori_arr, {
    index: 1,
    item: {
       id: 3,
       name: 'she',
       age: 44
    }
}))

If you tried logging it you'd see that inside your function insertItem you have a param called action, it's value (when you call it) is

action = { action: { index: 1, item: { id: 3, name: 'she', age: 44 }}}

so when you try to access action.item it doesn't exist.

Another solution would be to change your function to

function insertItem(array, action) {
  return [
    ...array.slice(0, action.action.index),
    action.action.item,
    ...array.slice(action.action.index)
  ]
}
🌐
WebDevAssist
webdevassist.com › typescript › typescript-add-to-array-if-doesnot-exists
TypeScript program to add an element to an array if it does not ...
But instead of using push, we have to use unshift. unshift adds an element to the start of an array. So, we can rewrite the above program as like below: let strArray = Array.of('one', 'two', 'three', 'four'); strArray.indexOf('zero') === -1 ? strArray.unshift('zero') : console.log('It is already ...
🌐
Index.dev
index.dev › blog › conditionally-add-objects-to-typescript-arrays
How to Conditionally Add Objects to Arrays in TypeScript
Learn how to add objects to arrays conditionally in TypeScript using simple conditional statements, functional methods, and type guards.
🌐
C# Corner
c-sharpcorner.com › UploadFile › 5089e0 › array-object-in-typescriptpart3
Array Object In TypeScript: Part 3
May 18, 2020 - The TypeScript Array object stores multiple values in a single variable at a time. TypeScript provides many methods. In this article, I am describing some of the TypeScript array methods. In TypeScript the push() method inserts one or more elements at the last position in an array.
Top answer
1 of 5
34
let myArray = [];
let commentData = {} as Dish;
commentData.id = 3;
commentData.name = 'something';
myArray.push(commentData);

It will work...

2 of 5
10

#Answer

Answer on how to push Comment (object) into Dish.comments (array) in TypeScript.


export interface Dish {
   id: number;
   name: string;
   image: string;
   category: string;
   label: string;
   price: string;
   featured: boolean;
   description: string;
   // comments: Comment[]; // remove this
   comments: Array<Comment>; // <--- change to this. everytime you want to add array use Array<YourInterface>
}

export interface Comment {
   rating: number;
   comment: string;
   author: string;
   date: string;
}

dish.comments.push(commentData);

View live code on TypeScript Playground and click RUN.

As you see in the above code. You need to change Comment[] into Array<Comment>.

#Explanation

Generic Type Variables

Array<T> or Array<Type>

You may already be familiar with this style of type from other languages such as Java and C#.

We have Generic Type Variables in typescript too.

Another way to use Generic Type Variables:

Here's an example of an array with multiple types:


let x: Array<string | number>
x = ["hello", "world", 2]

This second version is common if your array consists of different types of objects. For example:

interface Boat {
  name: string
}

interface SpaceShip {
  code: number
}

interface Wagon {
  active: boolean
}

let inventory: Array<Boat | SpaceShip | Wagon> = [];

let boatData: Boat = {
  name: "Boat 1"
}

let spaceShipData: SpaceShip = {
  code: 1234
}

let wagonData: Wagon = {
  active: true
}

inventory.push(boatData);
inventory.push(spaceShipData);
inventory.push(wagonData);

console.log(inventory);

View live code on TypeScript Playground and click RUN.

You can learn more about Generic Type Variables here and here

🌐
GeeksforGeeks
geeksforgeeks.org › typescript › add-an-object-to-an-array-in-typescript
Add an Object to an Array in TypeScript - GeeksforGeeks
August 5, 2025 - In this approach we are using splice method which can be used to add elements at a specific index. An object can only be added without deleting any other element by specifying the second parameter to 0. Example: This example uses splice method ...
Find elsewhere
🌐
Educative
educative.io › answers › how-to-add-one-or-more-elements-to-an-array-in-typescript
How to add one or more elements to an array in TypeScript
Similar to JavaScript, which is a subset of TypeScript, we can add elements to an array using the unshift() method.
🌐
AlgoCademy
algocademy.com › home › mastering typescript: conditionally add object to array with ease
Mastering TypeScript: Conditionally Add Object to Array with Ease
October 12, 2024 - Learn to conditionally add objects to arrays in TypeScript with practical examples and best practices.
🌐
Medium
dpericich.medium.com › how-to-push-elements-to-a-typescript-array-ea9a899687f8
How to Push Elements to a TypeScript Array | by Daniel Pericich | Medium
June 12, 2022 - I tried to do the same thing for creating an array in JavaScript using TypeScript and got the following error: ... Figure 1. Never type error message for pushing elements to an array.
🌐
HowToDoInJava
howtodoinjava.com › home › typescript › typescript array
TypeScript Array or List (with Examples)
April 9, 2024 - Learn to create an array, add/remove items, and iterate over array items along with cloning and merging the arrays in TypeScript.
🌐
React
react.dev › learn › updating-arrays-in-state
Updating Arrays in State – React
This is because you’re not mutating the original state, but you’re mutating a special draft object provided by Immer. Similarly, you can apply mutating methods like push() and pop() to the content of the draft. Behind the scenes, Immer always constructs the next state from scratch according to the changes that you’ve done to the draft. This keeps your event handlers very concise without ever mutating state. You can put arrays into state, but you can’t change them.
🌐
TypeScript
typescriptlang.org › docs › handbook › 2 › objects.html
TypeScript: Documentation - Object Types
push("hello!");Property 'push' does not exist on type 'readonly string[]'.2339Property 'push' does not exist on type 'readonly string[]'. ... Much like the readonly modifier for properties, it’s mainly a tool we can use for intent. When we see a function that returns ReadonlyArrays, it tells us we’re not meant to change the contents at all, and when we see a function that consumes ReadonlyArrays, it tells us that we can pass any array into that function without worrying that it will change its contents.
🌐
TutorialsPoint
tutorialspoint.com › home › typescript › typescript array push method
TypeScript Array Push Method
December 18, 2016 - Master the Array Push method in TypeScript. Learn to add elements to arrays effectively with our detailed guide.
🌐
SPGuides
spguides.com › push-an-object-into-an-array-in-typescript
How to Push Objects into an Array in TypeScript
May 6, 2025 - In this article, I’ll explain multiple ways to add objects to arrays in TypeScript, highlighting best practices I’ve learned from real-world projects. So, let’s dive in! TypeScript arrays are strongly typed, meaning they can be restricted to contain specific types of elements. This provides compile-time type checking, which helps catch errors before your code runs. Here are the different methods to push ...
🌐
TypeScript
typescriptlang.org › play › javascript › javascript-essentials › objects-and-arrays.ts.html
TypeScript: Playground Example - Objects and Arrays
Try re-writing this below: Copy this in the next line, character by character: purchaseOrder.item.type TypeScript provides feedback to the playground about what JavaScript objects are available in this file and lets you avoid typos and see additional information without having to look it up in another place. TypeScript also offers these same features to arrays.
🌐
GeeksforGeeks
geeksforgeeks.org › typescript-array-push-method
TypeScript Array push() Method - GeeksforGeeks
July 12, 2024 - The Array.push() method in TypeScript is a built-in function used to append one or more elements to the end of an array. It modifies the original array and returns the new length of the array. ... Return Value: This method returns the length of the new array. The method returns the new length of the array after the elements have been added.