타입스크립트 클래스

c_yj·2022년 10월 13일
0

TypeScript

목록 보기
6/7
post-thumbnail

클래스(class)

클래스는 객체지향형 프로그래밍의 기본 단위로서 객체를 생성하는 템플릿과 같은 기능을 한다. JavaScript는 Prototype에 기초한 클래스 개념을 가지고 있는데, 이는 C#, Java와 같은 객체지향형 프로그래밍 언어를 사용하는 개발자에게 익숙하지 않은 개념이다. TypeScript에서는 C#, Java에서 사용하는 클래스 개념과 유사한 클래스를 사용하며, class 라는 키워드 사용하여 클래스를 구현한다.
TypeScript에서 클래스를 정의하는 간단한 예제를 먼저 들어 보면 아래와 같다.

class Shape {
    name: string;
 
    constructor(name: string) {
        this.name = name;
    }
 
    draw(x: number, y: number) {
        console.log("Draw " + this.name + " at " + x + "," + y);
    }
}

readonly

속성 앞에 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를 사용하면 constructor() 함수에 초기 값 설정 로직을 넣어줘야 하므로 다음과 같이 인자에 readonly 키워드를 추가해서 코드를 줄일 수 있습니다.

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

Accessor

클래스 속성을 엑세스하면서 필터링이나 간단한 체크를 수행할 때, 흔히 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';

❗ get만 선언하고 set을 선언하지 않는 경우에는 자동으로 readonly로 인식됩니다.

Abstract Class

추상 클래스(Abstract Class)는 인터페이스와 비슷한 역할을 하면서도 조금 다른 특징을 갖고 있다. 추상 클래스는 특정 클래스의 상속 대상이 되는 클래스이며 좀 더 상위 레벨에서 속성, 메서드의 모양을 정의한다.

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

출처
https://joshua1988.github.io/ts/guide/classes.html#accessor
http://typescriptstudy.com/ts/article/14-%ED%81%B4%EB%9E%98%EC%8A%A4-class

profile
FrontEnd Developer

0개의 댓글