Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
414 views
in Technique[技术] by (71.8m points)

typescript - 类型的打字稿修复错误参数不可分配(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.

(每个对象都有一个名为id的属性,我想从给定的数据中获取最后一个id 。)

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));

(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

(链接)

  ask by John Chucks translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

(您的数据(我不喜欢这个名字)声明是Object,但是应该像这样:)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...