Develop/TypeScript

[Typescript] 타입스크립트 세팅하기

dawonny 2023. 7. 22. 02:02
728x90
반응형

tsconfig 파일 생성하기

프로젝트 폴더에 tsconfig.json 이라는 파일을 생성한다.

여기에는 ts 파일을 js 파일로 변환할 때에 어떻게 변환할지 세부설정을 작성할 수 있다.

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
    }
}

target : ts 파일을 어떤 버전의 js 로 바꿔줄지 정하는 부분

module : js 파일간 import 문법을 구현할 때 어떤 문법을 쓸지 정하는 부분

(예를 들어 commonjs 는 require 를 쓰고, es2015 는 import 를 쓴다)

 

그 밖에 추가로 넣을 수 있는 것들이 몇가지 있는데 다음과 같다.

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "noImplicitAny": true,
        "strictNullChecks": true
    }
}

noImplicitAny : any 라는 타입이 의도치 않게 발생할 경우 에러를 띄워주는 설정

strictNullChecks : null, undefined 타입에 이상한 조작을하면 에러를 띄우는 설정

 

이 외에는 아래를 참고하자.(전체는 여기서 확인할 수 있다  https://www.typescriptlang.org/tsconfig )

{
 "compilerOptions": {

  "target": "es5", // 'es3', 'es5', 'es2015', 'es2016', 'es2017','es2018', 'esnext' 가능
  "module": "commonjs", //무슨 import 문법 쓸건지 'commonjs', 'amd', 'es2015', 'esnext'
  "allowJs": true, // js 파일들 ts에서 import해서 쓸 수 있는지 
  "checkJs": true, // 일반 js 파일에서도 에러체크 여부 
  "jsx": "preserve", // tsx 파일을 jsx로 어떻게 컴파일할 것인지 'preserve', 'react-native', 'react'
  "declaration": true, //컴파일시 .d.ts 파일도 자동으로 함께생성 (현재쓰는 모든 타입이 정의된 파일)
  "outFile": "./", //모든 ts파일을 js파일 하나로 컴파일해줌 (module이 none, amd, system일 때만 가능)
  "outDir": "./", //js파일 아웃풋 경로바꾸기
  "rootDir": "./", //루트경로 바꾸기 (js 파일 아웃풋 경로에 영향줌)
  "removeComments": true, //컴파일시 주석제거 

  "strict": true, //strict 관련, noimplicit 어쩌구 관련 모드 전부 켜기
  "noImplicitAny": true, //any타입 금지 여부
  "strictNullChecks": true, //null, undefined 타입에 이상한 짓 할시 에러내기 
  "strictFunctionTypes": true, //함수파라미터 타입체크 강하게 
  "strictPropertyInitialization": true, //class constructor 작성시 타입체크 강하게
  "noImplicitThis": true, //this 키워드가 any 타입일 경우 에러내기
  "alwaysStrict": true, //자바스크립트 "use strict" 모드 켜기

  "noUnusedLocals": true, //쓰지않는 지역변수 있으면 에러내기
  "noUnusedParameters": true, //쓰지않는 파라미터 있으면 에러내기
  "noImplicitReturns": true, //함수에서 return 빼먹으면 에러내기 
  "noFallthroughCasesInSwitch": true, //switch문 이상하면 에러내기 
 }
}

 


파일 변환

ts 파일은 js 랑 똑같이 사용 가능하다.

하지만 웹 브라우저는 ts 파일을 이해하지 못해 js 파일로 변환작업을 해야한다.

js 파일로 변환하려면 터미널에 다음과 같이 입력하면 ts 파일을 js 파일로 변환을 해준다.

tsc -w

그리고 html 파일 등에서 ts 로 작성한 코드를 사용하려면

변환된 .js 파일을 사용하면 된다.


 

이미 있는 React 프로젝트에 설치하려는 경우

작업 경로 터미널에서 다음을 입력한다.

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

새로운 React 프로젝트를 만든다면

npx create-react-app my-app --template typescript

 


간단 문법 정리

// 변수 만들 때 타입 지정가능
// 타입으로 쓸 수 있는 것 : string, number, boolean, bigint, null, undefined,[], {} 등
let 이름 :string = 'kim'; 

// array
let namelist :string[] = ['kim', 'park', 'lee'];

// object
// ?는 있어도 되고 없어도 되는 옵션
let nameObject :{name:string, age?:number} = {name:'kim'}; 

// string 또는 number 타입
let nameOrAge :string|number = 'kim'; 

// type으로 별칭을 지어줄 수 있다.
type myType = string|number; 
let alias :myType = 'kim';

// 함수는 파라미터와 return 값이 어떤 타입인지 지정해줄 수 있다.
function 함수(x:number) : number{
  return x * 2;
}

// 튜플 타입
type Member = [number, boolean]; 
let john :Member = [1, true];

type Member1 = {
  name : string;
}

// object안에 어떤 속성이 들어갈 지 모를 때 타입지정 한번에도 가능
// index signature
type Member2 = {
  [key :string]:string, // 글자로 된 모든 object 속성의 타입은 string이다.
}
let john2 :Member2 = {name:'kim', age:'20'};

// class
class User{
  name :string;
  constructor(name:string){
    this.name = name;
  }
}

ref : 코딩애플

728x90
반응형