Laura
Laura

Reputation: 99

element is not typed at array object and receive messages of error

I get this message In my const Icons[link.label], but Icons has type:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'iconsProps'. No index signature with a parameter of type 'string' was found on type 'iconsProps'

I don't know how resolve this error

Code:

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

Icons.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
}

Thanks for any help!

Upvotes: 0

Views: 111

Answers (1)

Mic Fung
Mic Fung

Reputation: 5692

Typescript cannot recognise link.label is one of the keys in iconProps. Therefore, we can cast it explicitly to notify typescript.

From:

Icons[link.label]

To:

Icons[link.label as keyof iconsProps]

Upvotes: 1

Related Questions