TypeScript for JavaScript Programmers

TypeScript adds a additional layer on top of JS : type system

Type Composing

Structural Type System

구조적 타입 시스템에서 두 객체가 같은 형태를 가지면 같은 것으로 간주

interface Point {
  x: number;
  y: number;
}

function printPoint(p: Point) {
  console.log(`${p.x}, ${p.y}`);
}

// "12, 26"를 출력합니다
const point = { x: 12, y: 26 };
printPoint(point);

TS, the Basic

JS는 동적 타입만을 제공하며, 런타임에만 확실히 어떤 일이 벌어지는지 알 수 있음

정적 타입검사를 도입해 코드를 실행하기 전에 예측하자!

→ 오타, 호출되지 않은 함수, 논리 오류, 예외가 아닌 실행 실패 등을 코드를 실행하기 전에 발견하고 잡을 수 음

tsc, TypeScript Compiler

npm install -g typescript

// tsc 에러 뜨면  -> package.json에 
tsc --noEmitOnError hello.ts

// tsconfig.json 생성
tsc --init

strict 모드 사용을 위해 package.json “script”에 명령어 추가

실행할 때, 뒤에 컴파일 할 ts 파일명만 추가하면 됨

TypeScript는 ES3라는 아주 구버전의 ECMAScript를 타겟으로 동작 → es2020으로 동작하도록 바꿔줄 수 있음

— strict

noImplicitAny : 타입이 any로 암묵적으로 추롲되는 변수에 대하여 오류를 발생시킴

strictNullChecks : null, undefined 처리 확인

Documentation - Everyday Types