我遇到打字稿掉毛的问题。场景是数据来自包含对象数组的API。
[
{
"id": 3,
"name": "politics",
"slug": "politics",
},
{
"id": 2,
"name": "sport",
"slug": "sport",
},
{
"id": 1,
"name": "weather",
"slug": "weather",
}
]
我想要的是创建任何新对象并尝试在服务器上发布之前,我们必须确保slug
是否唯一。因此,我创建了一个名为uniqueStr
的实用程序函数,该函数将检查段塞是否存在。
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
行,打字稿短绒给出了一个错误。
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'.
答案 0 :(得分:1)
您可以使用indexable-types来指定Category
接口实例的属性可以通过字符串索引访问。
示例:
interface Category {
id: number;
name: string;
slug: string;
parent: number;
[key: string]: number | string;
};
答案 1 :(得分:-1)
试试这个
const index = this.selectedActors.findIndex((a: { name: any; }) => a.name === actor.name);
以前用这个
const index = this.selectedActors.findIndex((a => a.name === actor.name);