【问题标题】:element is not typed at array object and receive messages of error未在数组对象中键入元素并接收错误消息
【发布时间】:2021-07-17 03:41:45
【问题描述】:

我在我的 const Icons[link.label] 中收到此消息,但 Icons 的类型为:

元素隐式具有“any”类型,因为“string”类型的表达式不能用于索引类型“iconsProps”。在“iconsProps”类型上找不到带有“string”类型参数的索引签名

我不知道如何解决这个错误

代码:

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.labeliconProps 中的键之一。 const Icon = Icons[link.label as keyof iconsProps]
  • 谢谢! @MicFung 我想将您的答案标记为已解决!
  • 谢谢。刚刚在下面回答。
  • 如果您输入的是links,那么您可以在Link 的标签属性类型上断言keyof IconPropsdemo,而不是强制转换link.label

标签: javascript reactjs typescript next.js


【解决方案1】:

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

发件人:

Icons[link.label]

收件人:

Icons[link.label as keyof iconsProps]

【讨论】:

    猜你喜欢
    • 2011-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-08
    • 1970-01-01
    相关资源
    最近更新 更多