1
votes

I have an object called Item, I have defined an interface that contains its fields, and an array of fields that can be changed and defined. When the user wants to update the item, he sends a POST request with the updated item, and I go through the array and update the fields according to the user's data. The problem is that Typescript throws an error: Type 'string | number 'is not assignable to type' never '. Type 'string' is not assignable to type 'never'.ts (2322)

I would appreciate any help on the subject

interface Item {
    id?: number;
    title?: string;
    price?: number;
}

const requiredItemFields: Array<keyof Item> = [
    "title",
    "price",
]

app.post('/update-item', (req, res) => {
    const existItem: Item = req.body.item;
    const newItem: Item = {};
    for (let filed of requiredItemFields) {
        if (existItem.hasOwnProperty(filed)) {
            newItem[filed] = existItem[filed]; << ERROR
        }
    }
})

Typescript Playground

1

1 Answers

1
votes

The thing is typescript is not as smart as you think.

When you do :

newItem[filed] = existItem[filed];

typescript doesn't assume that newItem[filed] will be of the same type as existItem[filed].

To it, existItem[filed] could be of any type behind Item keys.

As an validation of what I'm saying, we can see that the following is working :

newItem[filed as 'id'] = existItem[filed as 'id'];

What solution do you have ?

Force typescript to accept the affectation "I know what I'm doing, theses two values are of the same type".

newItem[filed] = existItem[filed] as any;

or

// @ts-ignore
newItem[filed] = existItem[filed];