본문 바로가기

개발에 도움이 되는/TypeScript

TypeScript 개념 및 설치 방법 (React)

- TypeScript 

JavaScript의 SuperSet(상위 확장)인 오픈소스 프로그래밍 언어이다.

동적 타입인 JavaScript는 소규모일 땐 편할지 몰라도 대규모 혹은 다른 사람과 협업을 해야 되는 상황에서는 동적 타입은 직관적으로 어떤 타입의 변수인지 알 수 없어 치명적이다. TypeScript는 JavaScript에 Type 문법을 더하여 이러한 문제를 해소하고자 나왔다. 또한 에러 메시지 수준도 올라갔다.

 

- 기본 설치 (기본 html + css + typescript 개발 시)

 1) typescript 설치 (global)

npm install -g typescript

 2) tsconfig.json 생성 후 아래 내용 작성

{
  "compilerOptions": {
    "target": "es5",  // 자바스크립트 몇 버전으로 컴파일할 것인지
    "module": "commonjs",  // 모듈 import를 언제적 자바스크립트 문법으로 할 것인지
  }
}

 3) 트랜스파일러 자동 실행

tsc -w

 

 

 

- React에서의 TypeScript 사용 방법

 1) CRA로 시작하기

npx create-react-app [프로젝트 이름] --template typescript

 1-1) 만약 기존에 있는 CRA에 설치하고 싶다면

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

 

  2) CRA로 시작했다면 tsconfig.json가 자동으로 생성되지만 그렇지 않은 경우 tsconfig.json을 생성 후 아래 내용 작성

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": [
    "src"
  ]
}

 3) type에 따라 확장자명을 tsx or ts로 code 작성

 

참고 : 기존에 설치했던 library 앞에 @types/를 붙여서 설치하면 typescript용으로 porting한 library로 설치가 된다.

 ex)

// 기존 JavaScript 이용 시 설치 방법
npm i styled-components

// TypeSciprt 이용시 설치 방법
npm i @types/styled-components

 

반응형