[TIL] 속시원한 리액트 타입스크립트
타입스크립트는 양면적입니다. 타입 체킹을 통한 에러 방지와 에디터의 자동완성 지원이라는 장점의 반면에 타입 에러를 어떻게 해결해야 할지 모르는 상황에 자주 처한다는 단점도 존재합니다. 그래서 리액트에서의 타입스크립트 사용을 주된 내용으로 하는 강의를 들어봤습니다.
https://www.udemy.com/course/react-typescript-the-practical-guide/
컴포넌트
타입스크립트 컴포넌트 정의방법은 다양합니다. 가장 극악은 클래스를 사용하는 것인데 다행히 실제 소스에서는 별로 보이지 않습니다. 함수로 정의하는 방법도 여러가지라는 것을 설명해 줍니다.
아래의 예에서 3번이 가장 올드한 스타일인데 제가 본 회사 프로젝트가 저래서 매우 머리 아팠습니다.
1. function CompoA({ title, children }: CompoAProps) {}
2. const CompoA = ({ title, children }: CompoAProps) => {}
3. const CompoA: FC<CompoAProps> = ({ title, children }) => {}다형적 컴포넌트
다음과 같이 <Button> 이라는 컴포넌트 명을 가지면서 href 속성이 있으면 <a> 가 되고, 없으면 <button> 이 되는 컴포넌트를 타입에러 없이 구현하는 예제를 통해 prop type의 사용에 대해 설명해 줍니다.
import { type ComponentPropsWithoutRef } from 'react';
type ButtonProps = ComponentPropsWithoutRef<'button'> & {href?: never};
type AnchorProps = ComponentPropsWithoutRef<'a'> & {href?: string};
function isAnchorProps(props: ButtonProps | AnchorProps): props is AnchorProps {
return 'href' in props;
}
export default function Button(props: ButtonProps | AnchorProps) {
if (isAnchorProps(props)) {
return <a className="button" {...props}></a>;
} else {
return <button className="button" {...props}></button>;
}
}useContext와 useReducer
redux toolkit 의 사용에 대한 전단계로 context 와 reducer 를 사용할 때의 typescript 로 인한 고려사항을 설명합니다.
fetch response 의 캐스팅
fetch 응답에 대해 type 정보가 사라지는 것에 대한 간단한 해결방법을 알려줍니다.
const data = (await get(
'https://jsonplaceholder.typicode.com/posts'
)) as RawDataBlogPost[];redux toolkit 과 타입스크립트
generic 함수인 useDispatch 와 useSelector 의 정확한 타입을 지정하여 사용하는 법을 알려줍니다.
export const useCartDispatch: DispatchFunction = useDispatch
export const useCartSelector: TypedUseSelectorHook<RootState> = useSelector결론
검색을 해 보면 “타입스크립트에서는 이렇게 하라” 라는 가이드는 있습니다만, 왜 그래야 하는지 모르는 경우가 대부분입니다. 이 강의는 그 이유를 바닥부터 설명해서 이해에 도달하게 합니다. 최고의 강의로 강추합니다.
