No overload matches this call.Overload 1 of 2, '(props: PolymorphicComponentProps<"web",FastOmitDetailedHTMLPropsButtonHTMLAttributesHTMLButtonElement>,HTMLButtonElement>, never>, void, void, {}, {}>): Element', gave the following error.
기존의 진행하던 프로젝트를 jsx문법에서 tsx로 마이그레이션 하던 중 위의 오류가 생겼다. 오류가 나타난 코드는 아래와 같다.
const renderPages = () => {
return Array.from({ length: pageNum }, (_, index) => (
<PageNums
key={index + 1}
onClick={() => handlePageClick(index + 1)}
activePage={index + 1 === productPageNum}
>
{index + 1}
</PageNums>
));
};
const PageNums = styled.button`
padding: 3px 8px;
border: none;
border-radius: 3px;
background: transparent;
font-size: 18px;
${(props) =>
props.activePage &&
css`
color: #fff;
background-color: var(--primary);
`}
`;
renderPages 함수 부분의 activePage
부분과 PageNums 스타일 컴포넌트 안의 activePage
부분에 빨간선이 생겼다.
No overload matches this call 오류가 발생하는 이유는 activePage
속성이 styled-components의 button 컴포넌트에 제대로 전달되지 않았기 때문이라고 한다. 즉, 타입 호환성의 문제였다. PageNums 컴포넌트를 타입 정의하는 부분에서 activePage
속성의 타입을 명시적으로 지정해주어야 한단다.
type PageNumsProps = {
activePage?: boolean;
} & ButtonHTMLAttributes<HTMLButtonElement>;
const PageNums = styled.button<PageNumsProps>`
padding: 3px 8px;
border: none;
border-radius: 3px;
background: transparent;
font-size: 18px;
${(props) =>
props.activePage &&
css`
color: #fff;
background-color: var(--primary);
`}
`;
먼저 PageNum 컴포넌트의 타입을 PageNumsProps라는 type으로 지정을 해준다. ButtonHTMLAttributes<HTMLButtonElement>
는 HTML 버튼 요소에 적용되는 기본 속성을 상속받은 타입이다. 즉 ButtonHTMLAttributes
generic을 HTMLButtonElement
로 지정하여서 <button>
요소에 적용되는 속성들을 포함하게 한다. 이렇게 하면 PageNums 컴포넌트는 <button>
요소에 적용되는 모든 기본 속성을 가지게 된다. activePage?: boolean
은 PageNumsProps에 새로운 속성인 activePage
를 정의하는 부분이고 activePage
는 optional 속성이므로 있을 수도 있고 없을 수도 있으며, boolean이기에 true와 false 값을 가진다. 따라서 PageNumsProps는 기본적 버튼 요소의 속성들을 상속 받으면서 추가적으로 activePage
속성을 가지는 타입이 정의 된다.