Trouble Shooting

[TypeScript] Element implicitly has an 'any' type because expression of type 'string' can't be used to index type "...".

dev_seon 2022. 12. 12. 21:55

1. 에러 발생

카드 컴포넌트에 조건에 맞는 이미지를 적용하기 위해 조건에 맞는 이미지의 key 값(string 타입)을 return하는 함수를 생성했습니다. 함수를 통해 얻은 key 값으로 이미지의 경로가 저장되어 있는 CardsImg 객체에 대괄호 표기법으로 접근하여 <img> 태그의 src 속성에 적용하려 하였으나, 다음과 같은 에러가 발생했습니다.

에러 내용
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type "...".
No index signature with a parameter of type 'string' was found on type "...". ts(7053)
// 에러 발생 코드
const Card = (data: CardProps) => {
  // 조건에 맞는 카드 이미지의 key 값을 string으로 반환하는 함수
  const selectCardImg = (type: string, occupation: string) => {
    return Object.keys(CardsImg).filter(
      (cardName) =>
        cardName.includes(type) && cardName.includes("_" + occupation)
    )[0];
  };

  return (
    <CardContainer>
      <Image
        src={CardsImg[selectCardImg(data.type, data.occupation)]} // 에러가 발생한 부분
        alt={`${data.occupation}Card`}
      />
    </CardContainer>
  );
};

 

2. 에러 해결

방법 1) String Literal type 적용

// CardsImgType 선언 (union type; string literal type 조합)
type CardsImgType = keyof typeof CardsImg 

const Card = (data: CardProps) => {
  const selectCardImg = (type: string, occupation: string) => {
    return Object.keys(CardsImg).filter(
      (cardName) =>
        cardName.includes(type) && cardName.includes("_" + occupation)
    )[0];
  };

  return (
    <CardContainer>
      <Image
        src={CardsImg[selectCardImg(data.type, data.occupation)] as CardsImgType} // type 적용
        alt={`${data.occupation}Card`}
      />
    </CardContainer>
  );
};

export default Card;

방법 2) Index Signature 선언

interface CardImgObj {
  [key: string]: any; // Index Signature 선언
}

// 객체에 CardImgObj 타입 지정
const CardsImg: CardImgObj = {
  project_card,
  study_card,
};

 

3. 고찰

에러 해결을 위해 에러에 대해 검색해보던 중 TypeScript는 기본적으로 string type의 key를 사용하는 것을 허용하지 않는다는 것을 알게되었습니다. TypeScript에서 객체의 key 값으로 객체에 접근하기 위해서는 string literal type의 key 값으로 접근하는 방법과  객체의 타입을 선언하고 정의할 때 index signature를 선언하는 방법이 있다는 것을 확인했고, 에러를 해결할 수 있었습니다.