javascript - 未在数组对象中键入元素并接收错误消息
问题描述
我在我的 const 中收到此消息Icons[link.label]
,但Icons
类型为:
元素隐含地具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“iconsProps”。在“iconsProps”类型上找不到具有“字符串”类型参数的索引签名
我不知道如何解决这个错误
代码:
import { Icons } from './Icons'
import links from './content'
import * as S from './style'
export type PropsIcons = {
color: string
height: string
width: string
margin: string
}
const SocialLinks = ({ color, height, width, margin }: PropsIcons) => {
return (
<>
<S.SocialLinksWrapper>
<S.SocialLinksList>
{links.map((link, i) => {
const Icon = Icons[link.label]
return (
<S.SocialLinksItem key={i}>
<S.SocialLinksLink
href={link.url}
title={link.label}
target="_blank"
rel="noopener noreferrer"
>
<S.IconWrapper
height={height}
width={width}
color={color}
margin={margin}
>
<Icon />
</S.IconWrapper>
</S.SocialLinksLink>
</S.SocialLinksItem>
)
})}
</S.SocialLinksList>
</S.SocialLinksWrapper>
</>
)
}
export default SocialLinks
图标.ts
import { Github } from '@styled-icons/boxicons-logos/Github'
import { Youtube } from '@styled-icons/boxicons-logos/Youtube'
import { Twitter } from '@styled-icons/boxicons-logos/Twitter'
import { Email } from '@styled-icons/entypo/Email'
import { StyledIcon } from 'styled-icons/types'
export type iconsProps = {
Github: StyledIcon
Twitter: StyledIcon
Youtube: StyledIcon
Email: StyledIcon
}
export const Icons: iconsProps = {
Github,
Twitter,
Youtube,
Email
}
谢谢你的帮助!
解决方案
Typescript 无法识别link.label
是iconProps
. 因此,我们可以将其显式转换为通知 typescript。
从:
Icons[link.label]
至:
Icons[link.label as keyof iconsProps]
推荐阅读
- c++ - 为什么代码调用 LValue 函数而不是 RValue 函数
- javascript - 解构对象时出现意外结果
- javascript - 根据其他对象值数组更新对象数组
- python - sorted 参数背后的语法是什么?
- javascript - 如何序列化 OpenTelemetry Javascript Span
- java - java中的DialogFlow快速入门示例不适合我
- mlp - 如何使用库查找 sklearn MLPClassifier 中的参数数量?
- google-assistant - Google Actions Console - 发布被拒绝
- pandas - 布尔过滤器 geopandas 数据框紧随其后
- python - 我应该如何将 BM25Okapi 对象值保存到文件中?