타입스크립트에서의 클래스
이 글은 타입스크립트에서의 클래스에 대해 설명합니다.
YouTube Video
타입스크립트에서의 클래스
타입스크립트의 클래스는 자바스크립트의 ES6 클래스에 기반하며 타입 표기와 접근 제한자 같은 추가 기능을 제공합니다. 이는 객체 지향 프로그래밍의 개념을 활용하면서 더 강력하고 명확한 타입 안정성을 보장합니다.
아래는 타입스크립트 클래스의 기본 사용법과 기능에 대한 설명입니다.
기본 클래스 정의
1class Person {
2 name: string; // Member variable
3 age: number; // Member variable
4
5 // Constructor
6 constructor(name: string, age: number) {
7 this.name = name;
8 this.age = age;
9 }
10
11 // Method
12 greet(): void {
13 console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
14 }
15}
16
17const person = new Person("Alice", 25);
18person.greet(); // Hello, my name is Alice and I am 25 years old.
name
과age
는 클래스의 속성(멤버 변수)입니다.constructor
는 클래스를 인스턴스화할 때 호출되는 메서드로, 매개변수를 받아 속성에 값을 할당합니다.greet
는 클래스의 메서드로,void
타입으로 반환값이 없음을 나타냅니다.
접근 제한자
타입스크립트에서는 접근 제한자(public
, private
, protected
)를 사용하여 클래스 속성과 메서드에 대한 접근을 제어할 수 있습니다.
public
기본적으로 모든 속성과 메서드는 public
입니다. 이는 클래스 외부에서 접근할 수 있음을 의미합니다.
1class Animal {
2 public species: string;
3
4 constructor(species: string) {
5 this.species = species;
6 }
7
8 public makeSound(): void {
9 console.log(`${this.species} makes a sound.`);
10 }
11}
12
13const animal = new Animal("Dog");
14console.log(animal.species); // Dog
15animal.makeSound(); // Dog makes a sound.
species
속성과makeSound
메서드는public
으로 선언되어 클래스 외부에서 접근할 수 있습니다.
private
private
제한자를 사용하면 클래스 외부에서 속성이나 메서드에 접근할 수 없습니다.
1class Car {
2 private brand: string;
3
4 constructor(brand: string) {
5 this.brand = brand;
6 }
7
8 public getBrand(): string {
9 return this.brand;
10 }
11}
12
13const car = new Car("Toyota");
14// console.log(car.brand); // Error: 'brand' is private and cannot be accessed.
15console.log(car.getBrand()); // Toyota
brand
속성은private
으로 선언되어 클래스 외부에서 접근할 수 없습니다.private
한정자를 사용하여 속성을 숨김으로써 데이터 캡슐화를 달성할 수 있습니다.
protected
protected
제한자는 클래스 외부에서의 접근을 차단하지만 하위 클래스(파생 클래스)에서는 접근할 수 있게 합니다.
1class Vehicle {
2 protected model: string;
3
4 constructor(model: string) {
5 this.model = model;
6 }
7}
8
9class Truck extends Vehicle {
10 public getModel(): string {
11 return this.model;
12 }
13}
14
15const truck = new Truck("Ford F-150");
16console.log(truck.getModel()); // Ford F-150
17
18// console.log(truck.model);
19// Error: Property 'model' is protected and only accessible within class 'Vehicle' and its subclasses.
model
속성은protected
로 선언되어 클래스 외부에서는 접근할 수 없지만, 하위 클래스에서는 접근할 수 있습니다.
Getter와 Setter
타입스크립트에서는 get
과 set
키워드를 사용하여 속성 값을 가져오거나 설정하는 getter와 setter를 정의할 수 있습니다.
1class Employee {
2 private _salary: number;
3
4 constructor(salary: number) {
5 this._salary = salary;
6 }
7
8 // Getter
9 get salary(): number {
10 return this._salary;
11 }
12
13 // Setter
14 set salary(newSalary: number) {
15 if (newSalary > 0) {
16 this._salary = newSalary;
17 } else {
18 console.log("Salary must be positive.");
19 }
20 }
21}
22
23const employee = new Employee(50000);
24console.log(employee.salary); // 50000
25employee.salary = 60000;
26console.log(employee.salary); // 60000
27employee.salary = -100; // Salary must be positive.
- 이 예제에서는
salary
속성에 getter와 setter를 사용하여 외부 접근 및 갱신을 제어합니다. setter는 음수 값을 방지하기 위해 유효성 검사를 수행하며, 잘못된 값이 제공되면 경고 메시지를 표시합니다.
상속
타입스크립트에서는 클래스를 상속할 수 있습니다. extends
키워드를 사용하여 부모 클래스에서 기능을 상속받을 수 있습니다.
1class Animal {
2 constructor(public name: string) {}
3
4 public move(): void {
5 console.log(`${this.name} is moving.`);
6 }
7}
8
9class Bird extends Animal {
10 public fly(): void {
11 console.log(`${this.name} is flying.`);
12 }
13}
14
15const bird = new Bird("Sparrow");
16bird.move(); // Sparrow is moving.
17bird.fly(); // Sparrow is flying.
- 이 예제에서
Bird
클래스는Animal
클래스를 상속받아Animal
의move
메서드를 사용할 수 있습니다. 또한, 자체적으로fly
메서드를 정의하여 상위 클래스의 기능을 상속받으면서 새로운 기능을 추가합니다.
추상 클래스
추상 클래스(abstract
)는 직접 인스턴스화할 수 없으며 하위 클래스에서 구체적인 구현을 제공하기 위한 템플릿으로 사용됩니다.
1abstract class Shape {
2 abstract getArea(): number;
3
4 public describe(): void {
5 console.log("This is a shape.");
6 }
7}
8
9class Circle extends Shape {
10 constructor(private radius: number) {
11 super();
12 }
13
14 public getArea(): number {
15 return Math.PI * this.radius * this.radius;
16 }
17}
18
19const circle = new Circle(5);
20console.log(circle.getArea()); // 78.53981633974483
21circle.describe(); // This is a shape.
- 이 예제에서
Shape
는 추상 클래스로 정의되며,getArea
는 하위 클래스에서 반드시 구현해야 하는 추상 메서드입니다.Circle
클래스는 이 추상 클래스를 상속받고 자체적으로 원의 넓이를 계산하는getArea
메서드를 구현합니다. 또한,describe
와 같은 구체적인 메서드는 공통 기능으로 상속되어 그대로 사용할 수 있습니다.
인터페이스와의 관계
클래스는 인터페이스를 구현하여 특정 속성과 메서드를 갖추도록 할 수 있습니다.
1interface Flyable {
2 fly(): void;
3}
4
5class Airplane implements Flyable {
6 public fly(): void {
7 console.log("The airplane is flying.");
8 }
9}
10
11const airplane: Flyable = new Airplane();
12airplane.fly(); // The airplane is flying.
- 이 예제에서
Flyable
인터페이스는fly
메서드의 명세를 정의하며,Airplane
클래스는fly
메서드에 대한 구체적인 정의를 제공하여 이 인터페이스를 구현합니다. 이로써Flyable
타입으로 취급할 수 있는 모든 객체는 반드시fly
메서드를 갖게 됩니다.
정적 멤버
클래스에서 정적 멤버를 정의하면, 해당 메서드와 속성은 클래스 자체와 연결됩니다. 정적 멤버는 클래스를 인스턴스화하지 않고도 호출할 수 있습니다.
1class MathUtils {
2 static PI: number = 3.14;
3
4 static add(a: number, b: number): number {
5 return a + b;
6 }
7}
8
9console.log(MathUtils.add(10, 20)); // 30
10console.log(MathUtils.PI); // 3.14
- 정적 메서드는
static
키워드를 사용하여 정의합니다. - 이 예제에서
MathUtils
클래스는 정적 메서드add
와 정적 속성PI
를 정의합니다. - 정적 멤버는 클래스 인스턴스에 속하지 않고, 클래스 자체에서 직접 호출할 수 있습니다.
요약
TypeScript 클래스는 JavaScript 클래스 기능에 타입 안전성, 접근 제한자 및 추상 클래스와 같은 기능들을 추가합니다. 이 기능을 통해 더 강력하고 안전한 객체 지향 프로그래밍이 가능합니다.
위의 기사를 보면서 Visual Studio Code를 사용해 우리 유튜브 채널에서 함께 따라할 수 있습니다. 유튜브 채널도 확인해 주세요.