【发布时间】:2020-03-19 05:50:07
【问题描述】:
我遇到了 Typescript linting 的问题。场景是数据来自包含对象数组的 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 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'.
【问题讨论】:
-
我认为答案是stackoverflow.com/questions/56833469/… 希望对您有所帮助。
-
@Jérôme 我已经看到了这个问题,但没有用。
标签: typescript