打字稿错误:类型“字符串"不能用于索引类型 X

编程入门 行业动态 更新时间:2024-10-27 14:30:58
本文介绍了打字稿错误:类型“字符串"不能用于索引类型 X的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送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], or ageMap["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:关键词]

本文发布于:2023-04-29 10:03:55,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   字符串   索引   错误   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!