Typescript 数组find method error元素隐式具有';任何';类型
我面临着打字稿脱毛的问题。场景是数据来自包含对象数组的APITypescript 数组find method error元素隐式具有';任何';类型,typescript,Typescript,我面临着打字稿脱毛的问题。场景是数据来自包含对象数组的API [ { "id": 3, "name": "politics", "slug": "politics", }, { "id": 2, "name": "sport", "slug": "sport", }, { "id": 1, "name": "weather", "slug": "weather", } ] 我想要的是,在创建任何新对
[
{
"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元素[property]==compareValue
Typescript 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'.
您可以使用指定属性可以通过字符串索引访问类别
接口的实例
例如:
接口类别{
id:编号;
名称:字符串;
段塞:字符串;
家长:人数;
[键:字符串]:数字|字符串;
};
试试这个
const index = this.selectedActors.findIndex((a: { name: any; }) => a.name === actor.name);
早些时候使用的是这个
const index = this.selectedActors.findIndex((a => a.name === actor.name);
我想答案是希望它有帮助。@Jérôme我已经看到了这个问题,但没有起作用。谢谢你的回答。你能告诉我为什么我在
数据方面遇到问题。在尝试添加对象时取消移位TS2345:类型“Category”的参数不能分配给类型“never”的参数。
const Category:Category={id:1,name:name,slug:uniqueStr('slug',slug,data),父级:1};数据。取消移位(类别)代码>