【问题标题】:array find method error element implicitly has an 'any' type数组查找方法错误元素隐式具有“任何”类型
【发布时间】: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'.

【问题讨论】:

标签: typescript


【解决方案1】:

您可以使用indexable-types 来指定可以通过字符串索引访问Category 接口实例的属性。

例子:

interface Category {
    id: number;
    name: string;
    slug: string;
    parent: number;
    [key: string]: number | string;
};

【讨论】:

  • 谢谢你的回答你能告诉我为什么我在尝试添加对象时遇到data.unshift 的问题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);
【解决方案2】:

试试这个

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

之前用这个

const index = this.selectedActors.findIndex((a => a.name === actor.name);

【讨论】:

    猜你喜欢
    • 2021-08-26
    • 2019-11-11
    • 1970-01-01
    • 1970-01-01
    • 2020-02-02
    • 1970-01-01
    • 1970-01-01
    • 2021-11-11
    相关资源
    最近更新 更多