프내기
[Styled-component] Styled component에 props 넘기기(with TS) 본문
No overload matches this call.
탭 컴포넌트를 구현 중 overload라는 처음 보는 단어를 담은 에러메시지를 보았다
목표
커스텀 스타일드 컴포넌트인 <TabButton/>에 focused라는 props를 넘겨 true/false 냐에 따라 선택된 탭을 표시하기.
에러
해결
props를 넘기는 중에 다음과 같은 에러가 났다.
"No overload matches this call."
오버로드는 저그의 인구수를 늘려주는 유닛으로써 100미네랄을 주면 뽑을 수 있습니다
overload란 정확히는 function overloading이라는 함수와 관련된 개념이다.
동일한 이름의 함수에서 들어오는 매개변수의 type에 따라 다른 코드를 실행하는 것을 말한다.
ts에서는 각 함수의 매개변수의 개수도, 타입도 같아야 실행된다.
물론 다른 언어는 이름만 같으면 실행된다.
(날카로운 타스의 세계)
//overloaded function
function plus(a: string, b: string): void;
function plus(a: number, b: number): void;
function plus(a: any, b: any): void{
if(typeof a === 'number'){
console.log(a+b );
}
if(typeof a === 'string'){
console.log(`${a}, ${b}`);
}
};
plus(1,2); // 3
plus('my name', 'is venny'); // my name, is venny
plus(1, 'my name'); // error: No overload matches this call.
함수 명이 이렇게 겹쳐도 안에 매개변수 타입만 맞으면 알아서 해준다니 신기하다.
정리하면
overloaded functiond에서 지정해준 타입들 ((string, string), (number, number))과 실제로 전달한 매개변수의 타입((number, string))의 타입 형식이 일치하지 않아서 나온 에러였다.
// 넘길 props의 타입형식 선언
interface TabSelected {
focused: boolean;
}
...
return (
...
<TabButton focused={isSelected === 0} onClick={() => handleSelectedTab(0)}>내가 만든 투표</TabButton>
<TabButton focused={isSelected === 1} onClick={() => handleSelectedTab(1)}>참여한 투표</TabButton>
...
)
};
// 타입 지정
const TabButton = styled.button<TabSelected>`
width: 50%;
text-align: center;
padding-bottom: 10px;
border-bottom: ${props => props.focused === true ? `1px solid black` : `1px solid white`};
cursor: pointer;
`;
타입을 지정해주니 깔끔히 해결되었다!
그런데
매섭게 들어오는 warning 메시지.
browser: "boolean 타입 속성이 아닌 "focused"가 true를 받았네?"
me: "네? 저는 분명 focused에 boolean 타입까지 지정해서 넘겨줬는데요?"
browser: "않이;;; HTML태그 속성에 "focus"란거 없자나;;"
me: "그럼 HTML 태그 속성에 안넘어가게끔 하면 되는거죠?"
browser: "dd"
아래 Note 부분을 잘보자.
prefix로 $을 붙이면 해당 속성이 DOM에 넘겨지지않는다고 한다.
// 수정
interface TabSelected {
$focused: boolean;
}
...
// 수정
return (
...
<TabButton $focused={isSelected === 0} onClick={() => handleSelectedTab(0)}>내가 만든 투표</TabButton>
<TabButton $focused={isSelected === 1} onClick={() => handleSelectedTab(1)}>참여한 투표</TabButton>
...
)
};
// 수정
const TabButton = styled.button<TabSelected>`
width: 50%;
text-align: center;
padding-bottom: 10px;
border-bottom: ${props => props.$focused === true ? `1px solid black` : `1px solid white`};
cursor: pointer;
`;
깰-꼼.
끝
'Trouble Shooting' 카테고리의 다른 글
[typescript] ~ is possibly 'undefiend' (0) | 2023.12.08 |
---|---|
[map / useState]파베에서 데이터 받아왔는데 배열에 업데이트가 안된다 (0) | 2023.11.30 |
[Promise]Property 'then' does not exist on type 'void' (0) | 2023.11.29 |
[Firebase]이미지object 를 File 형식으로 변환하기 (1) | 2023.11.29 |
[styled-components]Global style, Theme 적용 오류 (2) | 2023.11.21 |