타입스크립트
[TypeScript] - 타입 추론 as keyof typeof
위르겐
2023. 5. 10. 16:17
디벨킷 프로젝트를 타입스크립트로
마이그레이션하는 작업 중에
타입 추론에 대해 더 찾아볼만한 기회가 생겼다.
const contents = {
first: <FaqContents.First />,
second: <FaqContents.Second />,
third: <FaqContents.Thrid />,
fourth: <FaqContents.Fourth />,
};
{isOpen && (
<>
<S.QuestionContentsWrapper>
{ contents[key] }
</S.QuestionContentsWrapper>
<S.BottomLine />
</>
)}
FAQ를 보여주는 코드이며
Wrapper로 contents[key]를 감싸
contents의 key와 props로 받은 key가 일치할경우
해당 컴포넌트를 렌더링한다.
해당 파일을 tsx로 변환했을 때
아래의 오류가 나오는데
Contents 객체에 있는 key 값이
Contents객체의 key 중 하나가 아닌
다른 문자열인 경우 오류를 발생시키는 것을 의미한다.
typescript는 객체의 key와 value의 타입을 명확하게 추론하기 때문이다.
이를 해결하기 위해서
두 가지 방법이 있는데
첫 번째로는
type ContentsType = {
[key: string]: React.ReactNode;
};
객체의 키값과 밸류값을 명확하게 지정해준다음
const contents: ContentsType = {
first: <FaqContents.First />,
second: <FaqContents.Second />,
third: <FaqContents.Thrid />,
fourth: <FaqContents.Fourth />,
};
위와 같이 타입을 선언해주면된다.
두 번째로는
오늘 글을 쓰게 된 이유인 타입 단언 문법이다.
{isOpen && (
<>
<S.QuestionContentsWrapper>
{ contents[key as keyof typeof contents] }
</S.QuestionContentsWrapper>
<S.BottomLine />
</>
)}
as keyof typeof는 타입 단언 문법인데
여기에서
keyof typeof contents는
contents 객체의 프로퍼티 이름 중 하나이며
as 키워드를 사용하여 contents의 키값이랑 같다라고 명시해주는 것이다.
즉 위의 코드는
key 값이 contents 객체의 프로퍼티 이름 중 하나와 일치하면 해당 프로퍼티 값으로 렌더링하고
그렇지 않으면 'undefined'로 처리해준다.
한번에 와닿지는 않는데
어떻게 써야하는지는 알 것 같다.
타입스크립트도 공부할게 정말많구나..
반응형