2

I have this problem on assigning an array of objects to an interface based array

Currently I have this implementation on my interface item.ts

export interface IItem {
    id: number, text: string, members: any
}

and on the item.component.ts

export class ItemComponent {
    selectedItems: IItem[] = [];
    items: IExamItems;
    getSelected(): void {
        this.selectedItems = this.items.examItems.map(examItem=> examItem.item)
    }
}

it seems that i'm always getting this error

TS2322: Type 'IItem[][]' is not assignable to type 'IItem[]'.
Type 'IItem[]' is not assignable to type 'IItem'.
Property 'id' is missing in type 'IItem[]'.
4
  • 7
    We are yet missing IExamItems interface declaration Commented Jan 2, 2018 at 3:07
  • 1
    Yes definitely include the interface Commented Jan 2, 2018 at 5:13
  • Greg is right. If examItem.item is an IItem then please try a push each item and it should work. Do a console of this.items.examItems.map(examItem=> examItem.item) and you get the structure you are trying to assign. Seems like its a type mismatch Commented Jan 2, 2018 at 13:35
  • 1
    ah sorry forgot to include, but i've already declared it @Gary yes, thanks for pointing that out it is indeed a mismatch, and already got the solution as well Thank you :) Commented Jan 3, 2018 at 22:54

1 Answer 1

2

Your assignment doesn't work because as the error states, the value has an incompatible type with the field. You can't assign IItem[][] to IItem[], as the former is an array of arrays of IItem and the latter is just an array of IItem. You either need to flatten the array or change the type of selectedItems field to IItem[][]. If you want to flatten the array, you can use Array.prototype.concat:

const itemArr = this.items.examItems.map(examItem=> examItem.item);
this.selectedItems = Array.prototype.concat.apply([], itemArr);
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.