Study/TypeScript

[TS] Class

taecongs 2023. 10. 30. 11:07

 


알고있으면 좋은 Typescript Tip✨


TypeScript Class vs JavaScript Class

  • Typescript에서 사용되는 클래스의 기반은 Javascript이기 때문에 큰 차이는 없다.
  • 다만 Typescript에서 만의 고유한 확장 기능들이 존재한다.

 

(1) Class 작성 비교하기

  • 자바스크립트 Class 문법
class Car {
  constructor (color) {
    this.color = color;
  }
  start() {
    console.log("start");
  }
}

const bmw = new Car("red");

 

  • 타입스크립트 Class 문법
    • 타입스크립트에서는 this.color 부분에 color라는 프로퍼티가 Car에 없다고 경고가 뜬다.
    • 이런 경우 멤버 변수를 선언해줘야 문제를 해결할 수 있다.
class Car {
  // 먼저 선언을 해서 알려준다.
  color: string;	
  constructor (color: string) {
    this.color = color;
  }
  start() {
    console.log("start");
  }
}

const bmw = new Car("red");

 

(2) 접근 제한자

접근 범위 public protected private
클래스 내부 O O O
자식 클래스 내부 O O X
클래스 인스턴스 O X X
  • public : 어디서든지 접근할 수 있으며, 외부 인터페이스를 구성한다.
  • protected : 클래스 자신과 자손 클래스에서만 접근할 수 있으며, 내부 인터페이스를 구성한다.
  • private : 클래스 자신에서만 접근할 수 있으며, 내부 인터페이스를 구성한다.

 

(3) 접근 제한자 예제

class Animal {
  constructor(public name: string, protected age: number, private breed: string) {
    this.name = name;
    this.age = age;
    this.breed = breed;
  }

  protected talk() {
    console.log(`this animal's name is ${this.name}`);
  }
}

const animal = new Animal("Ruby", 2, 'tlrhfmwkqmwhd');

// error : 'talk' 속성은 보호된 속성이며 'Animal' 클래스 및 해당 하위 클래스 내에서만 액세스할 수 있다.
animal.talk();

class Dog extends Animal{
  constructor(name: string, age: number, breed: string) {
    super(name, age, breed);

    this.talk();
    console.log(this.age);
    
    // error : 'breed' 속성은 private이며 'Animal' 클래스 내에서만 액세스할 수 있다.
    console.log(this.breed);
  }
}


// this.talk(): this animal's name is Ruby
// this.age: 5
const dog = new Dog("Ruby", 5, 'tlrhfmwkqmwhd');
  • 접근 제한자는 멤버 변수 혹은 함수에서 사용이 가능하며, 생성자 파라미터를 접근 제한자로 선언해두고 받을 경우 암묵적으로 클래스 프로퍼티로 선언된다.
  • 위의 예제를 살펴보면 public이 아닌 이상 외부에서 접근이 불가능하고, 자식 클래스에서 protected 접근 제한자는 접근이 가능한 반면에 private은 접근이 불가능하다는 것을 알려주고 있다.

 

(3) 추상 클래스

  • abstract 키워드를 사용하며, 직접 인스턴스를 생성할 수 없고 상속만을 위해 사용된다.
abstract class Animal {
  // 추상 메서드
  abstract makeSound(): void;
  
  // 일반 메서드
  move(): void {
    console.log("move move move!");
  }
}

// 직접 인스턴스를 생성할 수 없다.
// new Animal(); // error : 추상 클래스의 인스턴스를 만들 수 없다.

class Dog extends Animal {
  // 추상 클래스를 상속한 클래스는 추상 클래스의 추상 메서드를 반드시 구현하여야 한다.
  makeSound(): void {
    console.log("Doooooog~");
  }
}

const dog = new Dog();
dog.makeSound();
dog.move();
  • 추상 클래스는 new로 직접 사용하는 것은 불가능하고, 상속을 통해 사용이 가능하다.
  • 인터페이스의 경우 모든 메서드가 추상 메서드이지만, 추상 클래스는 일반 메서드를 포함할 수 있다는 차이점이 있다.