문서의 이전 판입니다!
기존의 JavaScript는 재사용 가능한 component를 만들기 위해 함수와 prototype에 기반한 상속을 이용했습니다. 하지만 기존 객체지향에 익숙해 있는 개발자들에게는 상당히 생소한 개념이었죠. 그래서 ECMAScript 2015( ES6 )에서는 개발자들이 좀 더 쉽게 JavaScript Application을 구현할 수 있도록 전통적인 class 기반의 객체지향 개념을 도입했습니다.
TypeScript 역시 이 class기반의 객체지향 기법을 이용해 Application을 개발할 수 있습니다.
일단 ECMAScript 2015( ES6 )의 class는 다음과 같이 정의하고 사용할 수 있습니다.
class Book { constructor(btitle,bauthor) { this.btitle = btitle; this.bauthor = bauthor; } printInfo() { console.log(`제목: ${this.btitle}, 저자: ${this.bauthor}`); } } let book = new Book('젊은 베르테르의 슬픔','괴테'); book.printInfo();
위의 코드는 data type의 정보를 포함하고 있지 않기 때문에 TypeScript로 변형하면 오류가 발생합니다. 적절히 타입 정보를 포함해 코드를 수정하면 다음과 같습니다.
class Book { btitle: string; bauthor: string; constructor(btitle:string, bauthor:string) { this.btitle = btitle; this.bauthor = bauthor; } printInfo(): void { console.log(`제목: ${this.btitle}, 저자: ${this.bauthor}`); } } let book:Book = new Book('젊은 베르테르의 슬픔','괴테'); book.printInfo();
위의 코드는 Java에서 우리가 익히 보아왔던 class의 형태입니다. 생성자를 표현하는 부분이 좀 생소하지만 쉽게 이해할 수 있을 듯 합니다.
일반적인 객체지향언어의 Inheritance 개념 역시 TypeScript에도 사용할 수 있습니다. 다음의 코드를 보죠.
class Book { btitle: string; bauthor: string; // 상위 클래스의 생성자 constructor(btitle:string, bauthor:string) { this.btitle = btitle; this.bauthor = bauthor; } // 상위 클래스의 method // 입력 인자가 있으면 사용하고 없으면 default 사용 printInfo(input:string = 'Initial'): void { console.log(input); console.log(`제목: ${this.btitle}, 저자: ${this.bauthor}`); } } // class의 상속 class EBook extends Book { btype: string; constructor(btitle:string, bauthor:string, btype:string) { // 상위 class 생성자 호출 super(btitle, bauthor); this.btype = btype; } // method overriding printInfo(): void { // 상위 class의 method 호출 super.printInfo(); console.log(`제목: ${this.btitle}, 저자: ${this.bauthor}, 타입: ${this.btype}`); } } // IS-A relationship에 의한 상위 class type 사용 let book:Book = new EBook('젊은 베르테르의 슬픔','괴테', 'PDF'); // dynamic binding에 의한 overriding method 호출. book.printInfo();
기존 class를 확장하여 새로운 class를 정의하는 방법입니다. IS-A Relationship 역시 성립합니다. 그로 인한 상위 타입으로 객체를 사용할 수 있습니다. 또한 위의 예에서 처럼 method overriding의 개념 역시 존재하고 dynamic binding 개념 역시 존재합니다. 물론 TypeScript에서는 공식적으로 저 용어를 사용하지는 않습니다. 다만 우리가 Java언어에서 알고 있던 객체지향 개념이 그대로 TypeScript에도 일부 적용된다고 보시면 됩니다.