报错:Element implicitly has an ‘any’ type because expression of type ‘string’ can’t be used to index type ‘ILineColor’.No index signature with a parameter of type ‘string’ was found on type ‘ILineColor’.

翻译过来:元素隐式具有 “any” 类型,因为类型为 “string” 的表达式不能用于索引类型 “ILineColor”。在类型 “ILineColor” 上找不到具有类型为 “string” 的参数的索引签名。

一、对象

先看看以下示例,我定义了一个colorList,以及一个currentIndex代表当前的一个状态,根据这个状态获取到对应的值。此时此刻就会出现以上的报错。

import { reactive, toRefs, onMounted } from 'vue';

export interface IAsset {
    currentIndex: string;
}
export interface ILineColor {
    [key: string]: any;
    important: string;
    other: string;
}
export interface IAreaColor {
    important: Array<string>;
    other: Array<string>;
}
export interface IColor {
    area: IAreaColor;
    line: ILineColor;
}
export default {
    name: 'AssetBusiness',
    setup() {
        const asset: IAsset = reactive({
            currentIndex: 'important',
        });
        const colorList: IColor = {
            area: {
                important: ['rgba(52, 223, 248, 0.2)', 'rgba(52, 223, 248, 0.5)'],
                other: ['rgba(255, 203, 121, 0.2)', 'rgba(255, 203, 121, 0.5)'],
            },
            line: {
                important: 'rgba(52, 223, 248, 1)',
                other: 'rgba(255, 203, 121, 1)',
            },
        };

        onMounted(() => {
            console.log(colorList.line[asset.currentIndex]);
        });
        return {
            ...toRefs(asset),
        };
    },
};

那么现在我们来讲一讲解决的办法。可以将ILineColor声明为any,这样就可以简单的解决。

export interface IColor {
    area: IAreaColor;
    line: any;
}

当然最好还是使用强类型,也可以如下这样写:

export interface ILineColor {
    [key: string]: string;
    important: string;
    other: string;
}

这要根据currentIndex的值来应对,如果它是number类型,可能就需要这样写(因为类型string的属性important不能赋给string索引类型number):

export interface ILineColor {
    [key: string]: any;
    important: string;
    other: string;
}

当然,我们还可以断言asset.currentIndex 的值是对象 colorList.linekey

colorList.line[asset.currentIndex as keyof ILineColor]
二、数组

还有一种情况,也会出现这种错误,如下我定义了一个color以及list,我想要筛选返回有值的一个新数组。

const color = {
    red: 'red',
    green: null,
    blue: null,
};
const list = ['red', 'green', 'blue'];
const newColor = list.filter((item) => color[item]);

那么我们可以如何解决呢?假设您使用的是TS3.4或更高版本,从编译器获得这种类型推断的最简单方法是使用常量断言。如下可以使用as constas const使编译器按照您设置的确切顺序推断出一个元组,该元组恰好由数组中的三个字符串文字组成(它甚至是一个只读元组)。

const color = {
    red: 'red',
    green: null,
    blue: null,
};
const list = ['red', 'green', 'blue'] as const;
const newColor = list.filter((item) => color[item]);
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐