TypeScript?

TypeScriptJavaScript의 상위 집합으로, JavaScript코드에 타입 지정을 할 수 있다. 스크립팅 언어인 JavaScript와 달리 TypeScript는 컴파일(트랜스파일) 언어로서 컴파일 시점에 타입을 검사하고, 컴파일의 결과물로 JavaScript파일을 생성한다. JavaScript는 실행을 시켜야 에러를 확인할 수 있었고 디버깅 또한 쉽지 않았기 때문에 실행 전에 정적으로 에러를 잡는 TypeScript가 이러한 문제를 해결해준다. 

 

 

위의 사진처럼 TypeScript의 인기는 계속해서 늘어나고 있다. 그 예로 AngularTypeScript를 정식 채택했고, 구글 또한 2017년 사내 표준 언어로 TypeScript를 채택했다. 

 

설치 및 사용

TypeScriptglobal로 설치해준다.

 

$ yarn global add typescript

 

글로벌로 설치하지 않고 로컬에 설치할 경우 다음과 같이 입력한다.

 

$ yarn add typescript --dev

 

 

tsconfig.json파일을 생성한다.

 

$ tsc --init

 

 

 

tsconfig.json설정

 

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "ES2015",
    "sourceMap": true,
    "outDir": "dist"
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules"]
}

 

modulecommonjs로 설정을 하면 JavaScript를 브라우저에서만 사용하는 언어가 아닌 일반적인 범용 언어로 사용할 수 있도록 하겠다는 의미이다.

 

target에서는 컴파일할 JavaScript의 ECMA버전을 명시한다.

 

sourceMapSourceMap을 생성할지 말지 여부를 나타낸다.

 

outDir에서는 컴파일한 결과를 저장할 디렉터리를 설정한다.

 

include는 컴파일할 파일의 범위를 설정한다. 반대로 exclude는 컴파일하지 않을 디렉터리 등을 설정한다.

 

위와 같이 설정을 하고 index.ts파일을 컴파일 할 경우, dist폴더에 index.jsindex.js.map파일이 생기게 된다.

 

// index.ts

const name: string = "kang";
const age: number = 20;
const gender: string = "male";

export const sayHi = (name: string, age: number, gender?: string): string => {
  return `Hi ${name}, age: ${age}, gender: ${gender}!`;
};

console.log(sayHi(name, age, gender));

 

Index.ts 파일을 생성하고 위와 같이 작성한다. 코드를 보면 기존의 JavaScript와는 다르게 각 변수와 sayHi함수의 인자들에 타입들을 명시해주고 있는 것을 볼 수 있을 것이다. 여기서 만약 string타입의 name에 숫자인 30을 넣을 경우 에러가 날 것 이다. TypeScript의 다른 문법들도 간단하게 알아보면, 일단 위에서 name, agegenderperson이라는 객체에 넣고 Human이라는 Interface를 설정해보자. 그럼 아래와 같이 작성할 수 있다.

 

// index.ts

interface Human {
  name: string;
  age: number;
  gender: string;
}

const person = {
  name: "kang",
  age: 20,
  gender: "male",
};

export const sayHi = (person: Human): string => {
  return `Hi ${person.name}, age: ${person.age}, gender: ${person.gender}!`;
};

console.log(sayHi(person));

 

위의 코드에서 person객체는 Human이라는 interface에서 설정한 형태의 값을 지니고, sayHistring형태로 리턴한다는 것을 한 눈에 알아볼 수 있다. 다음은 HumanClass형태로 선언해보자.

 

// index.ts

class Human {
  public name: string;
  public age: number;
  public gender: string;
  
  constructor(name: string, age: number, gender: string) {
    this.name = name;
    this.age = age;
    this.gender = gender;
  }
}

const kang = new Human("kang", 20, "male");

const sayHi = (person: Human): string => {
  return `Hi ${person.name}, age: ${person.age}, gender: ${person.gender}!`;
};

console.log(sayHi(kang));

 

아래가 컴파일된 index.js파일 내용이다.

 

// index.js

class Human {
    constructor(name, age, gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }
}
const kang = new Human("kang", 20, "male");
const sayHi = (person) => {
    return `Hi ${person.name}, age: ${person.age}, gender: ${person.gender}!`;
};
console.log(sayHi(kang));

 

 

코드를 작성하면서 매번 tsc를 입력하여 확인하기는 귀찮을 수 있다. tsc-watch를 사용하면 그러한 번거로움에서 벗어날 수 있다. 일단 tsc-watch를 설치하자.

 

$ yarn add -D tsc-watch

 

다음으로는 package.json에서 scripts를 수정해주어야 한다.

 

{
  ..
  "scripts": {
    "start": "tsc-watch --onSuccess \" node dist/index.js\" "
  },
  "devDependencies": {
    "tsc-watch": "^4.2.9",
    "typescript": "^4.0.2"
  },
  ..
}

 

yarn start를 입력하면 tsc-watch가 동작하게끔 위와 같이 입력해준다. 에러 없이 동작할 경우 dist폴더에 있는 컴파일된 index.js파일을 실행시킨다. 

 

 

 

'TypeScript' 카테고리의 다른 글

[TypeScript] typescript-eslint의 이해와 사용  (0) 2020.10.10

생강강

,