React TypeScript에서 ‘(props: Props) => Element[]’ 에러 해결하기

제목: React TypeScript에서 ‘(props: Props) => Element[]’ 에러 해결하기 문제: ‘(props: Props) => Element[]’ 타입은 ‘FunctionComponent’ 타입에 할당할 수 없습니다. TypeScript를 사용하여 React 프로젝트를 작업 중이라면, 다음과 같은 오류 메시지를 마주칠 수 있습니다: '(props: Props) …

title_thumbnail('

제목: React TypeScript에서 ‘(props: Props) => Element[]’ 에러 해결하기

문제: ‘(props: Props) => Element[]’ 타입은 ‘FunctionComponent’ 타입에 할당할 수 없습니다.

TypeScript를 사용하여 React 프로젝트를 작업 중이라면, 다음과 같은 오류 메시지를 마주칠 수 있습니다:

'(props: Props) => Element[]' 타입은 'FunctionComponent' 타입에 할당할 수 없습니다.
  'Element[]' 타입은 'ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any)>) | null) | (new (props: any) => Component<any, any, any)>' 타입의 다음 속성이 누락되었습니다: type, props, key  TS2322

원인

이 오류는 React 컴포넌트의 반환 값으로 JSX 요소 배열을 전달하려고 할 때 발생하며, 타이핑 오류가 발생합니다. 이 문제는 컴포넌트의 타입 선언에 있으며, 기대하는 타입과 실제 반환 값 간의 불일치입니다.

해결책

프로젝트의 요구사항과 개인적인 선호도에 따라 몇 가지 해결 방법이 있습니다:

해결책 1: JSX 요소를 컨테이너 안에 감싸기

가장 간단한 해결책은 JSX 요소를 컨테이너 요소로 감싸는 것입니다. 추가적인 DOM 요소를 렌더링하지 않는 React.Fragment 컴포넌트를 사용할 수 있습니다:

const SocialList: React.FC = (props: Props) => {
  const { websites } = props;

  const websiteElements = websites.map((website) => {
    const { name, src, url } = website;

    return (
      <a href="{url}">
        <img src="{src}" />
      </a>
    );
  });

  return (
    
      {websiteElements}
    
  );
};

또는 fragment의 약식 문법인 다음과 같이 사용할 수도 있습니다:

<>
  {websiteElements}
</>

해결책 2: 타입 단언 사용하기

코드를 간결하게 유지하고 싶다면, 타입 단언을 사용하여 타이핑 오류를 무시할 수 있습니다. 하지만 타입 단언은 신중하게 사용해야 합니다:

const SocialList: React.FC = (props: Props) => {
  const { websites } = props;

  return websites.map((website) => {
    const { name, src, url } = website;

    return (
      <a href="{url}">
        <img src="{src}" />
      </a>
    );
  }) as any;
};

해결책 3: TypeScript 오류 억제하기

특정 오류를 무시할 방법을 찾지 못한 경우, 해당 문제가 발생하는 줄에서 전체 TypeScript 오류를 주석을 사용하여 억제할 수 있습니다:

// @ts-ignore
const SocialList: React.FC = (props: Props) => {
  const { websites } = props;

  return websites.map((website) => {
    const { name, src, url } = website;

    return (
      <a href="{url}">
        <img src="{src}" />
      </a>
    );
  });
};

결론

React와 TypeScript를 함께 사용할 때, 이 블로그 포스트에서 다룬 것과 같은 타이핑 관련 문제를 마주치는 것은 흔한 일입니다. 오류의 원인을 이해하고 적절한 해결책을 적용함으로써 이러한 문제를 해결하고 TypeScript를 사용하여 React 애플리케이션을 원활하게 개발할 수 있습니다.

JSX 요소를 컨테이너로 감싸기, 타입 단언 사용, 또는 TypeScript 오류 억제 등은 모두 유효한 해결책입니다. 하지만 코드의 유지보수성과 가독성에 미치는 영향을 고려하여 신중하게 사용하세요.

좋은 코딩 하세요!

참고 자료 :

https://stackoverflow.com/questions/57651621/type-props-props-element-is-not-assignable-to-type-functioncomponent

같은 카테고리의 다른 글 보기 :

reactjs

Leave a Comment