[TypeScript] React -> TS

yongkini ·2022년 7월 19일
0

TypeScript

목록 보기
8/11

React -> TS 컨버팅

1) index.tsx error

최상위 컴포넌트인 index.tsx에서

const root = ReactDOM.createRoot(document.getElementById("root"));

위의 코드에서 아래와 같은

TS2345: Argument of type 'HTMLElement | null' is not assignable to parameter of type 'Element | DocumentFragment'.
Type 'null' is not assignable to type 'Element | DocumentFragment'.

에러를 리턴했다. 결과적으로 위의 에러는 특정 요소가(document.getElementById("root")) null 일 수 있는데, React.createRoot에는 null 이 들어갈 수 있는 상황이기에 이에 대해 처리를 하라는 소리이다. 따라서 이에 대해 타입을 as[Type Assertion(타입 단언)]로 지정해주던지 !를 써서 '절대로 null이 들어오지 않아!' 라고 타입스크립트한테 말해주면 된다.

const root = ReactDOM.createRoot(document.getElementById("root") as HTMLElement);
const root = ReactDOM.createRoot(document.getElementById("root")!);

결과적으로 위의 두가지 방법 모두 해결책이 될 수 있고, 모두 적절한 해결책이다.

2) @babel/preset-typescript

: 개발 단계에서 npm run start로 웹팩 및 바벨 컴파일 및 트랜스파일링이 이뤄지는데 이 단계에서 바벨에게 typescript 해석에 대한 여지를 주기위한 모듈이라고 생각하면 된다. 바벨의 트랜스파일링 과정에 위의 모듈이 있어야 바벨과 타입스크립트를 같이 쓸 수 있는 것이다.

profile
완벽함 보다는 최선의 결과를 위해 끊임없이 노력하는 개발자

0개의 댓글