// 선택된 Tab Menu에 따라 하이라이트가 이동
const left = menuEl.current?.children[index].offsetLeft;
const width = menuEl.current?.children[index].offsetWidth;
기존 프로젝트에 타입스크립트를 적용하기 위해, js 파일을 tsx 파일로 전환하자마자, offset
관련 프로퍼티가 전부 존재하지 않는다는 에러가 발생하였다.
타입스크립트가 offset
관련 프로퍼티의 타입을 추론하지 못하고 있는 듯하여 as
를 통해서 타입 단언을 해줘야 할 것 같았는데 어떤 타입으로 단언을 해줘야하는 지를 몰라서 키워드 이것저것 바꿔가며 열심히 검색해보았다..!!
마침 타입스크립트 공식 레포지토리에 올라온 이슈가 현재 상황과 비슷하여 쉽게 해결할 수 있었다!
Secondly, the return type is "Element", and Element has no property "offsetTop". You likely expect it to return a "HTMLElement", but this is not obvious to the compiler because it could just as well be a "SVGElement".
답변에 따르면, 컴파일러는 HTMLElement 타입이 리턴되는 지 SVGElement 타입이 반환되는 지 명확하게 알지 못하기 때문에 타입 단언 (type-assertion)을 해주어야 한다는 내용인 것 같았다.
// 선택된 Tab Menu에 따라 하이라이트가 이동
const left = (menuEl.current?.children[index] as HTMLElement).offsetLeft;
const width = (menuEl.current?.children[index] as HTMLElement).offsetWidth;
...
return (
...
<TabMenu ref={menuEl} purpose={purpose}>
{menuArr.map((name, idx) => (
<li
key={`${idx.toString()}-${name}`}
id={`${idx}`}
className={currentTab === idx ? 'focused' : ''}
onClick={handleBtnClick}
role="none"
>
{name}
</li>
))}
</TabMenu>;
)
menuEl
(ref)의 자식인 li
를 HTMLElement
로 타입 선언하니 offsetLeft
, offsetWidth
프로퍼티를 사용할 수 있게 되었다!
공식문서 뿐만 아니라 공식 repository의 이슈, PR을 꼼꼼히 확인하는 것도 에러 해결에 큰 도움이 된다는 것을 깨달았다! 👏