[TS] Chapter 5. Typescript 컴파일러 및 구성-클래스 & 인터페이스_클래스 기초

변진상·2023년 5월 30일
0

Typescript 학습

목록 보기
7/13

chapter 4는 JS es6에 관한 내용인데 이는 이미 학습한 내용이라서 skip

목표: 클래스의 기초를 학습한다.

Class

  • object의 blueprints
  • object가 어떤 property와 method를 가질지 설계
  • 여러개의 비슷한 object를 더 쉽게 만들수 있게 한다.

Object

  • instance of Class

Class의 선언과 instance 생성

class, constructor 예약어!

class Department {
  name: string;

  constructor(n: string) {
    this.name = n;
  }
}

const accounting = new Department("ACCOUNTING");
console.log(accounting.name);

ES5와 ES6에서의 Class

JS에서 Class의 개념은 ES6에 등장한 새로운 개념은 아니다. 기존에도 Class의 개념은 존재했지만 그 표현방식이 달랐기 때문에 다른 프로그래밍 언어를 사용하는 이들에게 혼란을 줄 수 있었다. 이를 해결하기 위해 ES6에서 그 표현법이 달라진 것이지 이전에도 존재한 개념이었다.

- ES5에서의 class 구현

"use strict";
var Department = /** @class */ (function () {
    function Department(n) {
        this.name = n;
    }
    return Department;
}());
var accounting = new Department("ACCOUNTING");
console.log(accounting.name);

- ES6에서의 class 구현

class Department {
    constructor(n) {
        this.name = n;
    }
}
const accounting = new Department("ACCOUNTING");
console.log(accounting.name);

this

this는 생성된 클래스의 구체적인 인스턴스를 참조한다.

메소드의 패러미터의 this에 대한 type 선언

아래와 같이 메소드에 접근할 경우, undefined를 띄운다.

const tmpAcc = { describe: accounting.describe };

tmpAcc.describe(); // => department: undefined

이를 방지하기 위해 class 내부에 메소드 선언부에 this:클래스명 형식으로 타입을 선언해주면 this에 해당하는 클래스의 명세에 맞지 않는 객체가 해당 메소드를 호출하면 에러를 띄운다.

describe(this: Department) {
  console.log("department:", this.name);
}

접근제어자 private

JS는 최근까지 기본적으로 public으로 접근제어자가 설정되어있다. 이를 TS에서는 private으로 지정해준다(JS의 최근 문법에서는 변수 앞에 #를 붙여줌으로써 이를 구현할 수 있다). 이는 JS의 런타임에 체크하는것이 아닌 컴파일 중 에러를 띄워 방지해준다.
(private, get, set 참고: https://ko.javascript.info/private-protected-properties-methods)

class Department {
  public name: string;
  private employees: string[] = [];
	...
}

약식 초기화

기본적으로 propety를 선언 후 constructor 안에서 this.propertyThing = ~~로 할당해주는 이중 초기화 방식을 constructor 선언부에서 접근제어자, property명, type을 명시해주는 것으로 간소화할 수 있다. 이를 약식 초기화라고 한다.

class Department {
  public id: string;
  private name: string;
  private employees: string[] = [];

  constructor(id: string, n: string) {
    this.id = id;
    this.name = n;
  }
  ...
}

위의 코드에서는 이중 초기화로 class 필드에 property를 선언 후 초기화를 직접 두 번 코드에 작성해준다. 이를 아래와 같이 약식 초기화할 수 있다.

class Department {
  // public id: string;
  // private name: string;
  private employees: string[] = [];

  // constructor(id: string, n: string) {
  //   this.id = id;
  //   this.name = n;
  // }

  constructor(public id: string, private name: string) {
    //   this.id = id;
    //   this.name = n;
  }
}

const testObj = new Department("id1", "Otter");

readonly modifier

초기화 이후에 변경되어서는 안되는 데이터에 대해 readonly 키워드를 더해주면 된다. TS에서만 에러를 체크해준다. 초기화 이후 값을 변경하려고 하면 에러를 띄운다.

profile
자신을 개발하는 개발자!

0개의 댓글