I'm facing a problem with Typescript linting. The scenario is that data is coming from the API which contains an array of objects.
[
{
"id": 3,
"name": "politics",
"slug": "politics",
},
{
"id": 2,
"name": "sport",
"slug": "sport",
},
{
"id": 1,
"name": "weather",
"slug": "weather",
}
]
What I want is when there any new object is created and tries to post on the server before that we have to make sure slug
is unique or not. So I created a utility function named uniqueStr
that will check that slug is exist or not.
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;
};
At the following line return element[property] === compareValue
Typescript linter is giving an error.
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'.