首页 > 解决方案 > 未在数组对象中键入元素并接收错误消息

问题描述

我在我的 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
}

谢谢你的帮助!

标签: javascriptreactjstypescriptnext.js

解决方案


Typescript 无法识别link.labeliconProps. 因此,我们可以将其显式转换为通知 typescript。

从:

Icons[link.label]

至:

Icons[link.label as keyof iconsProps]

推荐阅读