2

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'.
Ven Nilson
  • 969
  • 4
  • 16
  • 42

2 Answers2

2

You can use indexable-types to specify that properties an instance of the Category interface can be accessed via string index.

Example:

interface Category {
    id: number;
    name: string;
    slug: string;
    parent: number;
    [key: string]: number | string;
};
Ihor Sakailiuk
  • 5,642
  • 3
  • 21
  • 35
  • Thanks for your answer Could you tell me why I'm facing a problem with `data.unshift` when trying to add an object `TS2345: Argument of type 'Category' is not assignable to parameter of type 'never'.` `const category: Category = { id: 1, name: name, slug: uniqueStr('slug',slug, data), parent: 1 }; data.unshift(category);` – Ven Nilson Nov 23 '19 at 10:36
-1

Try this out

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

earlier is used this

const index = this.selectedActors.findIndex((a => a.name === actor.name);
Kazeem Quadri
  • 247
  • 3
  • 5