首页 > 解决方案 > 打字稿错误:类型“字符串”不能用于索引类型 X

问题描述

我有一个简单的代码:

const allTypes = { jpg: true, gif: true, png: true, mp4: true };
const mediaType = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
return Boolean(allTypes[mediaType]);

打字稿抱怨:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ jpg: boolean; gif: boolean; png: boolean; mp4: boolean; }'.
  No index signature with a parameter of type 'string' was found on type '{ jpg: boolean; gif: boolean; png: boolean; mp4: boolean; }'.  TS7

我想我需要mediaType当作keyof typeof allTypes,但不知道如何。请帮忙

为了完成,完整的代码是:

// these are all the types of media we support
const allTypes = { jpg: true, gif: true, png: true, mp4: true };

const MediaGallery = () => {
    const classes = useStyles();
    const [ filters, setFilters ] = useState(allTypes);
    return (
        <div className={classes.root}>
            {mediaList
                .filter(({ url }) => {
                    const type = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
                    return Boolean(filters[type]);
                })
                .map(({ url, caption, hash }) => <Media url={url} caption={caption} key={hash} />)}
            <FiltersPanel onFiltersChanged={(newFilters: any) => setFilters(newFilters)} />
        </div>
    );
};

标签: typescript

解决方案


您只需要定义索引签名

const allTypes: {[key: string]: boolean} = { jpg: true, gif: true, png: true, mp4: true };

可索引类型

与我们如何使用接口来描述函数类型类似,我们也可以描述我们可以“索引”到的类型,比如a[10], 或ageMap["daniel"]。可索引类型有一个索引签名,它描述了我们可以用来索引对象的类型,以及索引时相应的返回类型。举个例子:

interface StringArray {
  [index: number]: string;
}

let myArray: StringArray;
myArray = ["Bob", "Fred"];

let myStr: string = myArray[0];

上面,我们有一个StringArray具有索引签名的接口。这个索引签名表明,当 aStringArray被 a 索引时number,它将返回 a string

实用程序类型:Record<Keys, Type>

另一种解决方案是使用 TypeScript 实用程序类型Record<Keys, Type>

构造一个对象类型,其属性键为Keys,其属性值为Type。此实用程序可用于将一种类型的属性映射到另一种类型。

const allTypes: Record<string, boolean> = { jpg: true, gif: true, png: true, mp4: true };

for (const key of Object.keys(allTypes)) {
  console.log(`${key}: ${allTypes[key]}`);
}

推荐阅读