Typescript 문서 - 04

Typescript 문서 - 04

Classes

class

class Greeter { // 새로운 클래스 선언
  greeting: string;
  constructor(message: string) {
    this.greeting = message; // 클래스 맴버 참조
    }
    greet() {
      return "Hello, " + this.greeting;
    }
}

console.log(new Greeter("world").greet()); // 클래스의 인스턴스 생성, 객체를 생성, 초기화

Inheritance

상속받아 기존 클래스를 확장하여 새로운 클래스를 생성할 수 있다.
class Animal {
  name: string;
  constructor(theName: string) { this.name = theName; }
  move(distanceInMeters: number = 0) {
    console.log(`${this.name} moved ${distanceInMeters}m.`);
  }
}

class Horse extends Animal {
  constructor(name: string) { super(name); }
  move(distanceInMeters = 45) {
    console.log("Galloping...");
    super.move(distanceInMeters);
  }
}

let tom: Animal = new Horse("Tommy the Palomino");
tom.move(34);

// output
// Galloping...
// Tommy the Palomino moved 34m.
extends 키워드를 사용하여 상속받는다. 상속받은 클래스는 기본 클래스에서 super()를 호출해야 한다.(상속받은 클래스에서 생성자 함수를 사용하는 경우에)

public, private and protected

public

기본은 public이다. 위의 Animal 클래스의 경우 특별히 쓰여져 있지 않았지만, public으로 인식된다.
class Animal {
  public name: string;
  public constructor(theName: string) { this.name = theName; }
}

private

private로 선언된 클래스는 외부 클래스에서 사용할 수 없다.
class Animal {
  private name: string;
  constructor(theName: string) { this.name = theName; }
}

protected

protectedsms private과 비슷하게 동작하지만, protected는 상속받은 클래스에서는 접근할 수 있다. 그러나 외부 클래스에서는 사용할 수 없다.

readonly

읽기 전용으로 속성을 만들 수 있다. 선언하거나 생성자에서 초기화해야 한다.
class Octopus {
  readonly name: string;
  readonly numberOfLegs: number = 8;
  constructor (theName: string) {
    this.name = theName;
  }
}

Getter/Setter

주의할 점
  • ECMAScript 5 이상 사용하도록 컴파일러 설정
  • get/set이 없는 속성은 자동으로 readonly로 추정된다.

static property

Abstract class

abstract인 클래스는 상속받아 하위 클래스에서 구현해주어야 한다.
abstract class Department {
  constructor(public name: string) { }
  printName(): void {
    console.log("Department name: " + this.name);
  }
  abstract printMeeting(): void;
}

class AccountingDepartment extends Department {
  constructor() {
    super("Accounting and Auditing");
  }
  
printMetting(): void {
  console.log("The Accouting Department meets each Monday at 10am.");
}

댓글

가장 많이 본 글