数组查找方法错误元素隐式具有“ any”类型

文·尼尔森

我遇到打字稿掉毛的问题。场景是数据来自包含对象数组的API。

[
  {
    "id": 3,
    "name": "politics",
    "slug": "politics",
  },
  {
    "id": 2,
    "name": "sport",
    "slug": "sport",
  },
  {
    "id": 1,
    "name": "weather",
    "slug": "weather",
  }
]

我想要的是什么时候创建任何新对象并尝试在服务器上发布,然后我们必须确保它slug是否唯一。因此,我创建了一个名为的实用程序函数uniqueStr,它将检查段塞是否存在。

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] === compareValueTypescript 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'.
伊霍尔·萨凯留克

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

例:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

绑定元素'Component'隐式具有'any'类型.ts

绑定元素“ title”隐式具有“ any”类型

绑定元素“posts”隐式具有“any”类型

函数隐式具有返回类型“ any”错误

错误消息:成员“ makes”隐式具有“ any”类型

错误:成员 'feedbackFormDirective' 隐式具有 'any' 类型的 angular

打字稿错误:TS7053元素隐式具有“ any”类型

React Navigation 5错误绑定元素'navigation'隐式具有'any'类型.ts

Nuxt-asyncData错误:“绑定元素'$ axios'隐式具有'any'类型。”

变量“ a”隐式具有“ any []”类型

参数隐式具有“ any”类型

Typescript错误:元素隐式具有“ any”类型,因为类型“ string”的表达式不能用于索引类型

Angular - 对象可能为“null”:错误 TS7052:元素隐式具有“any”类型,因为类型“AbstractControl”

元素隐式地具有“ any”类型,因为索引表达式不是“ number”类型。-索引签名错误

元素隐式具有 'any' 类型,因为类型 'typeof globalThis' 没有索引签名

元素隐式具有 'any' 类型,因为类型 '{}' 没有索引签名

React Typescript:元素隐式地具有“ any”类型,因为类型没有索引签名

Angular - 元素隐式具有“any”类型,因为“AbstractControl”类型没有索引签名

元素隐式具有“ any”类型,因为索引表达式不是“ number”类型[7015]

元素隐式地具有“ any”类型,因为类型“ any”的表达式不能用于索引类型

map()中的Typescript错误:元素隐式具有“ any”类型,因为类型“ string”的表达式不能用于索引类型

元素隐式具有 any 类型,因为时间表达式 any 不能用于索引类型

绑定元素“ dispatch”隐式具有“ any”类型。var dispatch:任何

元素隐式具有“ any”类型,因为ANGULAR中的type表达式

元素隐式具有“any”类型,因为“string”类型的表达式不能用于索引“Breakpoints”类型

元素隐式地具有“ any”类型,因为类型为string | 数字不能用于索引类型

元素隐式地具有“ any”类型,因为类型“ string”的表达式不能用于索引类型

元素隐式具有“any”类型,因为“string”类型的表达式不能用于索引“Palette”类型

元素隐式具有 'any' 类型,因为类型 'string' 的表达式不能用于索引类型 '{ AT: number; 是:数字,...}`