typescript - 打字稿错误:类型“字符串”不能用于索引类型 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>
);
};
解决方案
您只需要定义索引签名:
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
,它将返回 astring
。
实用程序类型: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]}`);
}
推荐阅读
- kubernetes-helm - 动态舵图配置的值层次结构
- jquery - 完整的日历显示错误的日期结束
- dart - dart 2.1 中的 Mixins - “on”关键字
- c++ - 开发 C++ sdl 库 setpixel 或 putpixel 示例代码请求
- java - 为什么Androidx.appcompat.AppCompatActivity会抛出java.lang.NoSuchMethodError: No virtual method getMainExecutor()?
- asp.net-core-mvc - 在 ASP.NET CORE 中使用 AJAX 在 DateTimePicker 中显示数据库中的用户生日
- javascript - 使用 onClick 按钮创建卡片元素的克隆
- node.js - puppeteer 如何获取元素 tagName
- wso2 - 如何在 2 个窗口上进行计算/比较?
- javascript - Reactjs 渲染两次