D
D
Destell2019-04-09 15:22:36
typescript
Destell, 2019-04-09 15:22:36

How to replace/add an array element correctly?

There are some items and their type
@observable items: Array<TCardItem> = [];

export type TCardItem = {
    id: string;
    photoUrl: string;
    name: string;
    lastname: string;
    phoneValues: Array<number | string>;
    address: string;
};

Further operations are performed with them
deleteItem = (id: string) => {
        this.items = this.items.filter(item => item.id !== id);
    };

saveItem = (id: string, modifiedItem: object) => {     
        this.items = this.items.map(item =>
            item.id === id ? modifiedItem : item
        );
    };

    addItem = (idItem: object) => {
        this.items = [...this.items, idItem];
    };

this.items in the second and third functions throw an error
Type "object[]" cannot be assigned to type "TCardItem[]".
Type '{}' is missing the following properties from type 'TCardItem': id, photoUrl, name, lastname, and 2 more.

I'm more than sure that this is happening because items is receiving Proxy {} data. What is the correct way to write a declaration for this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-04-09
@Destell

If items is an array of TCardItem, then you probably need to pass TCardItem to saveItem and addItem, not object:
By the way, why pass the id separately in saveItem? - it must be in modifiedItem.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question