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.
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.
Share Improve this question edited Jan 1, 2022 at 13:17 Peter Mortensen 31.6k22 gold badges109 silver badges133 bronze badges asked Sep 21, 2020 at 16:26 SanyamSanyam 892 silver badges7 bronze badges 3 |1 Answer
Reset to default 26The 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.
myArray
is defined as a tuple, not an array, type. You've said it should have exactly one entry..map
makes no such guarantee. Your initial type is probably wrong, or if you do only have one entry you don't need to.map
. – jonrsharpe Commented Sep 21, 2020 at 16:29myArray: [{ id: number; item: string; checked: boolean; }]
tomyArray: { id: number; item: string; checked: boolean; }[]
– Heretic Monkey Commented Sep 21, 2020 at 16:33