본문 바로가기
언어/TypeScript

Class 특성

by seacode 2025. 4. 14.

타입스크립트의 class 에 대해서 몇 가지 특성을 알아보자.

 

readonly

class Developer {
    readonly name: string;
    constructor(theName: string) {
        this.name = theName;
    }
}
let john = new Developer("John");
john.name = "John"; // error! name is readonly.

클래스의 멤버 앞에 readonly 를 붙이면, 읽기모드로만 접근 가능하다.

또한 readonly 를 쓰게되면 생성자 함수에다가 초기화 코드를 넣어줘야하므로, 아래와 같이 코드 길이를 줄일 수 있다.

class Developer {
  readonly name: string;
  constructor(readonly name: string) {
  }
}

 

Accessor

타입스크립트는 객체의 특성 속성의 접근 및 할당에 대해 제어가 가능하다.

이를 위해서 해당 객체는 클래스로 생성된 객체여야한다.

class Developer {
  name: string;
}
const josh = new Developer();
josh.name = 'Josh Bolton';

이렇게 일반적인 클래스 - 객체 예제가 있을 때, 추후 제약 사항을 추가하고 싶다면 get, set 를 쓴다.

class Developer {
  private name: string;
  
  get name(): string {
    return this.name;
  }

  set name(newValue: string) {
    if (newValue && newValue.length > 5) {
      throw new Error('이름이 너무 깁니다');
    }
    this.name = newValue;
  }
}
const josh = new Developer();
josh.name = 'Josh Bolton'; // Error
josh.name = 'Josh';

- set 함수에서 이름의 길이가 5 보다 크면 예외처리가 되도록 제약을 추가했다.

- 만약, get 만 선언하고 set이 없으면 자동으로 readonly 로 인식된다.

 

추상 클래스

앞서 봤던 인터페이스와 비슷하다.

다만, 추상 클래스는 특정 클래스의 '상속 대상' 이며, 보다 상위 레벨에서 속성과 메소드에 대한 정의를 내포한다.

abstract class Developer {
  abstract coding(): void; // 'abstract'가 붙으면 상속 받은 클래스에서 무조건 구현해야 함
  drink(): void {
    console.log('drink sth');
  }
}

class FrontEndDeveloper extends Developer {
  coding(): void {
    // Developer 클래스를 상속 받은 클래스에서 무조건 정의해야 하는 메서드
    console.log('develop web');
  }
  design(): void {
    console.log('design web');
  }
}
const dev = new Developer(); // error: cannot create an instance of an abstract class
const josh = new FrontEndDeveloper();
josh.coding(); // develop web
josh.drink(); // drink sth
josh.design(); // design web

'언어 > TypeScript' 카테고리의 다른 글

타입 추론  (0) 2025.04.15
제네릭(Generics)  (0) 2025.04.15
Union Type, Intersection Type  (0) 2025.04.14
enum 자료형  (0) 2025.04.13
인터페이스  (0) 2025.04.13