数组查找方法错误元素隐式具有"any"类型



我遇到了打字稿检查的问题。场景是数据来自包含对象数组的 API。

[
{
"id": 3,
"name": "politics",
"slug": "politics",
},
{
"id": 2,
"name": "sport",
"slug": "sport",
},
{
"id": 1,
"name": "weather",
"slug": "weather",
}
]

我想要的是,当创建任何新对象并尝试在服务器上发布时,我们必须确保slug对象是否唯一。所以我创建了一个名为uniqueStr的实用程序函数,它将检查 slug 是否存在。

ICategory.ts

export interface Category {
id: number;
name: string;
slug: string;
parent: number;
}

utility.ts

import {Category} from './ICategory';
export const uniqueStr = (property: string, compareValue: string, data: Category[]): string => {
if (Array.isArray(data) && data.length > 0) {
const objectFind = data.find((element) => {
return element[property] === compareValue;
});
// If not undefined
if (objectFind) {
const message = `${property} value should be unique.`;
alert(message);
throw new Error(message);
} else {
// Return value
return compareValue;
}
}
return compareValue;
};

在下一行return element[property] === compareValue打字稿 linter 给出错误。

TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Category'. No index signature with a parameter of type 'string' was found on type 'Category'.

可以使用可索引类型来指定可以通过字符串索引访问Category接口实例的属性。

例:

interface Category {
id: number;
name: string;
slug: string;
parent: number;
[key: string]: number | string;
};

试试这个

const index = this.selectedActors.findIndex((a: { name: any; }) => a.name === actor.name);

较早的是用这个

const index = this.selectedActors.findIndex((a => a.name === actor.name);

相关内容

最新更新