[TypeScript] 클래스

윤지·2024년 11월 23일

TypeScript

목록 보기
11/12
post-thumbnail

1. 타입스크립트 클래스의 특징

타입스크립트 클래스는 자바스크립트 클래스와 비슷한 구조를 가지며, 다음과 같은 차이점을 보유

  1. 타입 지정 가능: 속성과 메서드에 타입 명시 가능
  2. 접근 제어자: public, protected, private 키워드로 멤버의 접근 범위 제어 가능
  3. 추상 클래스 지원: 추상 메서드와 멤버를 포함 가능하며, 상속받는 클래스에서 구현 필요

2. 접근 제어자 (Public, Protected, Private)

타입스크립트는 클래스 멤버에 접근 제어자 사용 가능

접근 제어자의 종류

  • public (기본값): 어디서든 접근 가능
  • protected: 해당 클래스와 하위 클래스에서만 접근 가능
  • private: 해당 클래스 내에서만 접근 가능
class Car {
  public model: string; // 어디서나 접근 가능
  protected speed: number; // 해당 클래스와 하위 클래스에서만 접근 가능
  private year: number; // 클래스 내부에서만 접근 가능

  constructor(model: string, speed: number, year: number) {
    this.model = model;
    this.speed = speed;
    this.year = year;
  }

  private getYear(): number {
    return this.year;
  }
}

class Benz extends Car {
  constructor(model: string, speed: number, year: number) {
    super(model, speed, year);
  }

  maxSpeed(): number {
    return this.speed + 50; // protected 멤버 접근 가능
  }
}

const car = new Benz("Benz", 200, 2020);
console.log(car.model); // ✅ "Benz"
// console.log(car.speed); // ❌ protected 멤버에 직접 접근 불가
// console.log(car.year); // ❌ private 멤버에 직접 접근 불가

3. 추상 클래스

추상 클래스는 직접적으로 인스턴스 생성 불가

특정 클래스에서 구현해야 되는 걸 미리 정의할 때 사용

abstract 키워드로 추상 클래스와 추상 멤버를 선언

  • 추상(abstract) 멤버: 상속받는 클래스에서 반드시 구현 필요
  • 일반 멤버: 추상 클래스 내에서 이미 구현되어 있어 상속받는 클래스에서 선택적 오버라이드 가능
abstract class Animal {
  // abstract 멤버: 반드시 구현해야 함
  abstract makeSound(): void;

  // 일반 멤버: 이미 구현되어 있음
  eat(): void {
    console.log('먹는 중...');
  }
}

추상 클래스 예제

abstract class CarAbstract {
  abstract name: string;
  abstract color: string;
  abstract start(): void; // 구현 강제
  printInfo(): void {
    console.log(`${this.name}, ${this.color}`); // 구현된 메서드
  }
}

class Car extends CarAbstract {
  name: string;
  color: string;

  constructor(name: string, color: string) {
    super(); //상속
    this.name = name;
    this.color = color;
  }

  start(): void {
    console.log(`${this.name} is starting...`);
  }
}

const car = new Car("BMW", "Red");
car.start(); // "BMW is starting..."
//특정 메서드를 미리 완성시켜 두고 호출 가능
car.printInfo(); // "BMW, Red"

4. 인터페이스 구현 (Implements)

인터페이스는 클래스가 따라야 할 규칙(타입)을 정의

타입스크립트의 클래스는 implements 키워드로 인터페이스 구현 가능

인터페이스 구현 예제

interface Moveable {
  speed: number;
  move(): void;
}

interface Drivable {
  drive(): void;
}

class Car implements Moveable, Drivable {
  speed: number;

  constructor(speed: number) {
    this.speed = speed;
  }

  move(): void {
    console.log("Moving...");
  }

  drive(): void {
    console.log("Driving...");
  }
}

const car = new Car(100);
car.move(); // "Moving..."
car.drive(); // "Driving..."

💡 차이점:

  • 추상 클래스는 구현된 메서드와 속성 포함 가능, 인터페이스는 메서드와 속성의 형태만 정의

5. 제네릭 클래스

  • 제네릭(Generic)을 클래스에 적용 시 클래스가 다양한 타입의 데이터 처리 가능

제네릭 클래스 기본 예제

class Box<T> {
  value: T;

  constructor(value: T) {
    this.value = value;
  }

  getValue(): T {
    return this.value;
  }
}

const stringBox = new Box<string>("Hello");
console.log(stringBox.getValue()); // "Hello"

const numberBox = new Box<number>(123);
console.log(numberBox.getValue()); // 123

제네릭 클래스 상속

class Container<T> {
  value: T;

  constructor(value: T) {
    this.value = value;
  }

  getValue(): T {
    return this.value;
  }
}

class StringContainer extends Container<string> {
  constructor(value: string) {
    super(value);
  }

  print(): void {
    console.log("문자열 컨테이너 값:", this.value);
  }
}

const strContainer = new StringContainer("타입스크립트");
strContainer.print(); // "문자열 컨테이너 값: 타입스크립트"

6. 클래스 상속

class Vehicle {
  wheels: number;

  constructor(wheels: number) {
    this.wheels = wheels;
  }

  drive(): void {
    console.log(`Driving with ${this.wheels} wheels.`);
  }
}

class Car extends Vehicle {
  constructor() {
    super(4); // 부모 클래스의 생성자 호출
  }

  drift(): void {
    console.log("Drifting...");
  }
}

const car = new Car();
car.drive(); // "Driving with 4 wheels."
car.drift(); // "Drifting..."

출처: 수코딩

profile
프론트엔드 공부 기록 아카이빙🍁

0개의 댓글