본 포스트는 인프런의 타입스크립트 입문-기초부터 실전까지 강의(링크)를 듣고 정리한 내용입니다.


특정 값들의 집합을 의미하는 자료형

  • TS에서는 문자형과 숫자형 이넘 지원

enum Shoes { Nike, Adidas, NewBalance } const myShoes = Shoes.Nike; console.log(myShoes); // 0
  • 초기화를 하지 않으면 기본값은 숫자형(인덱스)
  • 첫 값에 대하여 1씩 증가하며, 초기화를 하지 않으면 0부터 시작

enum Shoes { Nike = '나이키', Adidas = '아디다스', NewBalance = '뉴발란스' } const myShoes = Shoes.Nike; console.log(myShoes); // '나이키'

이는 곧 아래와 같다.

const Shoes = {}; Shoes['Nike'] = '나이키'; Shoes['Adidas'] = '아디다스'; Shoes['NewBalance'] = '뉴발란스';

enum Answer { Yes = 'Y', No = 'N', } function askQuestion(answer: Answer) { if (answer === Answer.Yes) { console.log('정답입니다.'); } if (answer === Answer.No) { console.log('오답입니다.'); } } askQuestion(Answer.Yes); // 정답입니다. askQuestion('Yes'); // type이 Answer가 아니어서 오류
  • 함수에서 오타 등의 human error를 방지하기 위함

class Person { constructor(name, age) { this.name = name; this.age = age; console.log("생성되었습니다."); } } const seho = new Person("세호", 30); // 생성되었습니다. console.log(seho); // Person {name: "세호", age: 30}

자바스크립트는 프로토타입 기반 언어

// 프로토타입 미사용 const user = { name: "capt", age: 100 }; const admin = { name: "capt", age: 100, role: "admin" }; // 프로토타입 사용 const user = { name: "capt", age: 100 }; const admin = {}; admin.__proto__ = user; // prototype의 상위에 user를 두겠다. // 활용 console.log(admin.name); // capt console.log(admin.age); // 100
  • admin 객체는 빈 객체로 만들었으므로, prototype에 대한 정보가 없다.
  • admin.__proto__를 통해 admin의 prototype을 재지정
  • 데이터가 상속

프로토타입 사용 admin에 role을 추가해보자.

admin.role = "admin"; console.log(admin) // { role: "admin", __proto__: Object }
  • admin에 role 속성을 추가하면 그냥 admin을 출력하면 role에 대한 것만 직관적으로 출력
  • 상속 속성은 __proto__ 객체 내부에 상속 정보 확인 가능

// 기존 함수형 function Person(name, age) { this.name = name; this.age = age; } const capt = new Person("캡틴", 100); // 클래스(객체 지향형) class Person { constructor(name, age) { console.log("생성되었습니다."); this.name = name; this.age = age; } } const seho = new Person("세호", 30);

class Person { // 멤버 변수 type, scope 지정 private name: string; // 클래스 안에서만 사용 public age: number; // 전역에서 사용하는 경우 readonly log: string; // 값에 접근만 가능, 변경은 불가 constructor(name: string, age: number) { console.log("생성되었습니다."); this.name = name; this.age = age; } }
  • 멤버 변수의 type과 scope를 클래스 내부 최상단에 작성
  • 범위에 따라 앞에 붙는 문자가 달라짐(private, public, protected, ...)