4

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.

3
  • 2
    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. Commented Sep 21, 2020 at 16:29
  • 1
    Change myArray: [{ id: number; item: string; checked: boolean; }] to myArray: { id: number; item: string; checked: boolean; }[] Commented Sep 21, 2020 at 16:33
  • guys one of you should answer with that, not comment. Commented Sep 21, 2020 at 16:35

1 Answer 1

26

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.

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

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.