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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With