简体   繁体   中英

typescript fix error argument of type is not assignable

I don't know why I'm facing a problem. I have a function that takes an array of objects. Every object has a property named id and I wanted to get the last id from the given data. The code is working fine.

type Data = object;

const data = [
    {
        'id': 1,
        'name': 'Uncategorized',
    },
    {
        'id': 2,
        'name': 'DSLR Cameras',
    },
    {
        'id': 3,
        'name': 'Printer / Ink',
    },
];

const getLastId = (data: Data[]): number => {
    if (Array.isArray(data) && data.length > 0) {
        // Create an array of Id's of all items
        const idsArray: number[] = [];
        data.forEach((obj: { id: number }) => idsArray.push(obj.id));
        // Return last element id
        return idsArray[data.length - 1];
    } else {
        return 1;
    }
};

But, at the following line, an error is coming.

data.forEach((obj: { id: number }) => idsArray.push(obj.id));

TS2345: Argument of type '(obj: { id: number; }) => number' is not assignable to parameter of type '(value: object, index: number, array: object[]) => void'.
  Types of parameters 'obj' and 'value' are incompatible.
    Property 'id' is missing in type '{}' but required in type '{ id: number; }'.

What type of error it is and How to fix this? Link

Your Data (I do not like this name) declaration is Object, but should be like this:

type Data = {
    id: number,
    name: string,
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM