问题描述
限时送ChatGPT账号..我有一个简单的代码:
const allTypes = { jpg: true, gif: true, png: true, mp4: true };
const mediaType = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
return Boolean(allTypes[mediaType]);
TypeScript 抱怨:
TypeScript is complaining:
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
,但不知道如何处理.请帮忙
I think I need to treat mediaType
as keyof typeof allTypes
, but don know how. Please help
为了补全,完整代码为:
For sake of completion, the complete code is:
// 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>
);
};
);};
推荐答案
您只需要定义索引签名:
Indexable Types
可索引类型
<块引用>类似于我们如何使用接口来描述函数类型,我们也可以描述我们可以索引到"的类型,如 a[10]
或 ageMap[daniel";]代码>.可索引类型有一个索引签名,它描述了我们可以用来索引对象的类型,以及索引时相应的返回类型.举个例子:
Similarly to how we can use interfaces to describe function types, we can also describe types that we can "index into" like
a[10]
, orageMap["daniel"]
. Indexable types have an index signature that describes the types we can use to index into the object, along with the corresponding return types when indexing. Let’s take an example:
interface StringArray {
[index: number]: string;
}
let myArray: StringArray;
myArray = ["Bob", "Fred"];
let myStr: string = myArray[0];
上面,我们有一个带有索引签名的 StringArray
接口.这个索引签名表明,当一个 StringArray
被一个 number
索引时,它将返回一个 string
.
Above, we have a StringArray
interface that has an index signature. This index signature states that when a StringArray
is indexed with a number
, it will return a string
.
这篇关于打字稿错误:类型“字符串"不能用于索引类型 X的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论