Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloning an array of objects in TypeScript

I have an array of objects like below defined in my interface:

myArray: [{
    id: number;
    item: string;
    checked: boolean;
}]

I am trying to clone the array using the below statement:

let newArray = myArray.map(x => Object.assign({},x));

When I am trying to assign a new array to my original array, I am getting the below error:

Type '{ id: number; item: string; checked: boolean; }[]' is not assignable to type
'[{ id: number; item: string; checked: boolean; }]'.
  Target requires 1 element(s) but source may have fewer

It looks like the array of objects is being transformed to an object of array.

like image 841
Sanyam Avatar asked Nov 28 '22 00:11

Sanyam


1 Answers

The problem you're having lies in the difference between tuple and list types in TypeScript. Consider the following example Playground link:

type AsTuple = [number];

type AsArray = number[];

let myArrayA: AsArray = [];
let myArrayB: AsTuple = []; // This one errors

Why does the second one error? It's because AsArray is an array of numbers, whereas AsTuple is a tuple where the first (and only) item in the tuple is a number. An empty array doesn't conform to the type AsTuple; it must be a single item array.

In your example, you have:

myArray: [{
    id: number;
    item: string;
    checked: boolean;
}]

It defines myArray as a tuple type - it can have one item, which is an object. You could correct it by making it an an array type:

myArray: {
    id: number;
    item: string;
    checked: boolean;
}[]

You can see an example in this playground link.

like image 147
OliverRadini Avatar answered Nov 30 '22 13:11

OliverRadini