Javascript를 Typescript로 변환

Jayden ·2023년 1월 17일
0

1. Typescript 의존성 설치

npm install --save typescript @types/node @types/react @types/react-dom @types/jest

2. tsconfig 생성

npx tsc --init

3. 확장자 변경

'js' -> 'ts', 'jsx'-> 'tsx'로 확장자 변경

.ts로 변경

reportWebVitals.js → reportWebVitals.ts
setupTests.js → setupTests.ts

.tsx로 변경

App.js → App.tsx
App.test.js → App.test.tsx
index.js → index.tsx

3. tsconfig.config 파일 설정

1) but '--jsx' is not set.ts(6142) 오류 해결

compileOptions 옵션에서

jsx 설정을 주석해제 하고 값을 "react-jsx"로 변경한다.

2) Parameter 'e' implicitly has an 'any' type.ts(7006)

tsconfig.json 파일에서 "noImplycitAny"항목을 주석해제 시킨다.

이후에 확인해보면 Parameter 'e' implicitly has an 'any' type, ~ 라고 오류가 발생하는데 타입 추론이 가능하나, 보다 정확한 타입을 입력하라고 하는 메시지이다.

그래서 타입을 React.ChangeEvent<HTMLInputElement>로 설정하고, 정확한 타입 작성을 위해 tscoinfig.json 파일의 "noImplicitAny"는 다시 주석 처리 시켰다.

3) 'BrowserRouter' refers to a value, but is being used as a type here. Did you mean 'typeof BrowserRouter'

확장자를 App.js에서 App.tsx로 확장자 변경
index.js 파일에서도 동일한 오류가 있어 index.jsindex.tsx로 변경하였다.

<App.js>

4) Argument of type 'HTMLElement | null' is not assignable to parameter of type 'Element | DocumentFragment'.
Type 'null' is not assignable to type 'Element | DocumentFragment'.ts(2345)

<index.js>

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

로 변경한다.

5) reportWebVital.ts onPerEntry 타입 지정

import {ReportHandler} from "web-vitals";

const reportWebVitals = (onPerfEntry?: ReportHandler | undefined): void  => {
  if (onPerfEntry && onPerfEntry instanceof Function) {
    import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
      getCLS(onPerfEntry);
      getFID(onPerfEntry);
      getFCP(onPerfEntry);
      getLCP(onPerfEntry);
      getTTFB(onPerfEntry);
    });
  }
};

export default reportWebVitals;
profile
J-SONE 프론트엔드 개발자

0개의 댓글