constructor 키워드를 사용해 클래스 생성자 정의
따로 생성자를 정의하지 않았다면, 본문이 비어있는 함수가 생성자로 생성(constructor() {} ) 클래스 생성자를 통해 클래스 인스턴스가 생성될 때 실행될 로직 정의
class Dog {
constructor() {
console.log('constructing!');
}
}
const dog: Dog = new Dog(); // constructing!
클래스 내에서는 속성엔 this 키워드를 이용해 접근
모든 클래스 속성은 이름: 타입 꼴의 속성 선언을 통해 타입을 표기
class Triangle {
vertices: number;
constructor() {
this.vertices = 3;
}
}
const triangle: Triangle = new Triangle();
console.log(triangle.vertices); // 3
메소드 내에서는 this 키워드를 사용해 해당 메소드가 호출되는 인스턴스를 참조
class BarkingDog {
barkingSound: string;
constructor(barkingSound: string) {
this.barkingSound = barkingSound;
}
bark(): void {
console.log(this.barkingSound);
}
}
const barkingDog: BarkingDog = new BarkingDog(월!);
barkingDog.bark(); // 월!
접근제어자 종류:
public,private,protected
TypeScript의 클래스 문법은 ES6의 기능을 포함하면서 보다 강력한 기능 제공
접근 제어자를 통해 접근 가능한 범위 설정가능
각 속성에 데이터 타입지정 가능
class Book {
// public: 클래스 외부에서 접근 가능
public title: string;
// public은 기본 값으로 생략 가능합니다.
author: string;
// private: Book 클래스 내부에서만 접근 가능
private _manufacturing_plant: string;
// protected: Book 클래스를 포함한 서브 클래스에서만 접근 가능
protected paper_type: string;
constructor(title: string, author: string, public pages: number) {
this.title = title;
this.author = author;
this.pages = pages;
}
}
/* 인스턴스 생성 ------------------------------------------------ */
console.log(new Book('한 권으로 정리하는 4차 산업혁명', '최진기', 367));
속성과 마찬가지로 메서드 또한 접근 제어자를 사용해 외부에서의 접근 제어가능
접근 제어자가 붙은 생성자 매개변수는 같은 이름의 속성으로 선언되고, 해당 매개변수의 인자는 암묵적으로 인스턴스에 할당
class User {
constructor (public id: string, private password: string) { }
}
class User {
public id: string;
private password: string;
constructor (id: string, password: string) {
this.id = id;
this.password = password;
}
}
클래스 전체에서 공유되는 값이 필요한 경우, 스태틱 멤버(static member)를 사용
스태틱 멤버에는 클래스 이름을 사용해 접근 가능
class Counter {
static count: number = 0;
}
console.log(Counter.count); // 0
메소드 선언 앞에 static 키워드를 붙여 스태틱 메소드 정의
class Printer {
static print() {
console.log("print");
}
}
console.log(Printer.print()); // print
클래스는 extends 키워드를 사용해 기존에 존재하는 클래스 확장가능
클래스
A가 클래스B를 확장
A를B의 서브클래스(subclass)B를A의 슈퍼클래스(superclass)
슈퍼클래스의 생성자는 서브클래스의 생성자에서 자동 호출되지 않음
서브클래스의 생성자에선 super 키워드를 사용해 슈퍼클래스의 생성자를 호출
class 키워드 대신 abstract class 키워드를 사용해 추상 클래스 선언
일반 클래스는 extends 키워드를 사용해 추상 클래스를 확장
추상 클래스는 인스턴스화가 불가능
abstract class Animal {
move(): void {
console.log("roaming the earth...");
}
abstract makeSound(): void;
}
abstract class 키워드를 이용해 정의된 추상 클래스 Animal은 두 멤버가 존재
move 메소드는 일반 클래스 메소드와 동일
abstract 키워드가 앞에 붙어 있는 makeSound 는 abstract method로, 타입 정보 이외의 실제 구현은 포함하지 않음
가상 클래스를 확장하는 서브 클래스는 슈퍼 클래스의 모든 가상 메소드를 구현해야만 함