[TypeScript]Record를 사용해 String 값 JSX.Element에 적용하기

Song Haeun·2023년 9월 15일
0
const optionComponents = (index: number, isChecked: boolean) => {
    const components = {
      Text: (
        <Text
          appeal={appeal}
          setAppeal={setAppeal}
          index={index}
          isChecked={isChecked}
        />
      ),
      Image: <Image />,
      AudioRecord: <AudioRecord />,
      Video: <Video />,
    };

    return components[selectedOptions[index]] || <Text />;
  };```
  
  ```ts
return (
          ...
          </div>
          {optionComponents(index, isChecked)}
          ...
        </div>
        ...
)

위의 방식으로 선택한 태그를 불러오는 코드를 작성했다.

return components[selectedOptions[index]] || ; 에서 다음과 같은 문제 발생

'string' 형식의 식을 '{ Text: Element; Image: Element; AudioRecord: Element; Video: Element; }' 인덱스 형식에 사용할 수 없음

selectedOptions[index]는 string, components의 키와 값은 JSX.Element여서 생긴 문제 였다.

이 문제를 해결하기 위해 Record 형식을 사용했다.

Record

Record<string, JSX.Element> : 키가 문자열이고 값이 JSX 엘리먼트인 객체

  • Record는 TypeScript에서 사용되는 제네릭 형식(annotation) 중 하나로, 키-값 쌍의 객체를 나타내는 데 사용된다.
  • Record는 JSX 엘리먼트를 저장하고 관리하는 데 사용되며, 키를 사용하여 동적으로 엘리먼트를 선택할 때 유용하다.
   ...
    const components: Record<string, JSX.Element> = {
    ...
    return components[selectedOptions[index]] || <Text />;
  };

components 객체로 문자열 키를 사용하여 다른 JSX 엘리먼트를 저장하고, selectedOption에 따라 해당하는 엘리먼트를 반환할 수 있다.

profile
프론트엔드 개발하는 송하은입니다🐣

0개의 댓글