
타입스크립트의 클래스(Class)는 ES6의 클래스 문법을 기반으로 하며, 객체 지향 프로그래밍의 중요한 요소인 캡슐화, 상속, 다형성 등을 지원한다.
클래스는 객체의 특정한 유형을 정의하며, 속성(데이터 멤버)과 메서드(멤버 함수)를 가질 수 있다. 클래스를 사용하여 객체를 생성하려면 new 키워드를 사용하고, 생성자 메서드 constructor를 이용하여 초기화를 수행한다.
다음은 간단한 타입스크립트 클래스의 예입니다:
class Person {
name: string; // 속성
constructor(name: string) { // 생성자
this.name = name;
}
greet() { // 메서드
console.log(`Hello, my name is ${this.name}`);
}
}
let john = new Person('John');
john.greet(); // 출력: "Hello, my name is John"
타입스크립트 코드를 자바스크립트로 변환하면 다음과 같다:
class Person {
// 속성
constructor(name) { // 생성자
this.name = name;
}
// 메서드
greet() {
console.log(`Hello, my name is ${this.name}`);
}
}
let john = new Person('John');
john.greet(); // 출력: "Hello, my name is John"
타입스크립트는 또한 접근 제한자(Access Modifiers)를 제공한다. public, private, protected 등의 키워드를 사용하여 클래스 멤버의 접근 수준을 제어할 수 있다.
타입스크립트는 또한 클래스에서 상속을 지원한다. 즉, 한 클래스가 다른 클래스의 속성과 메서드를 상속받을 수 있다. 이는 extends 키워드를 사용하여 수행된다.
class Employee extends Person {
company: string;
constructor(name: string, company: string) {
super(name); // 부모 클래스의 생성자 호출
this.company = company;
}
greet() {
super.greet(); // 부모 클래스의 메서드 호출
console.log(`I work at ${this.company}`);
}
}
let jane = new Employee('Jane', 'Acme Corp');
jane.greet();
// 출력:
// "Hello, my name is Jane"
// "I work at Acme Corp"
이렇게 타입스크립트의 클래스는 객체 지향 프로그래밍의 특징을 잘 지원하며, 이를 통해 코드의 재사용성을 높이고, 관리하기 쉽고, 이해하기 쉬운 구조를 만들 수 있다.