[ts] 추상 클래스와 interface

추상 클래스란?

추상 메소드란?

abstract class User {
  constructor(protected firstName: string, protected lastName: string) {}
  // 추상 메소드
  abstract sayHi(name: string): string;
  abstract fullName(): string;
}

추상 클래스 특징

typescript로 추상 클래스 구현

abstract class User {
  constructor(protected firstName: string, protected lastName: string) {}
  abstract sayHi(name: string): string;
  abstract fullName(): string;
}
// protected 추상 클래스로부터 상속받은 클래스들이 property에 접근하도록 허용해준다

class Player extends User {
  sayHi(name: string) {
    return `Hello ${name}.`;
  }
  fullName() {
    return `${this.firstName} ${this.lastName}`;
  }
}

javascript로 빌드 code

class User {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
}

class Player extends User {
  sayHi(name) {
    return `Hello ${name}.`;
  }
  fullName() {
    return `${this.firstName} ${this.lastName}`;
  }
}

typescript interface 키워드로 추상 클래스 구현

interface User {
  firstName: string;
  lastName: string;
  sayHi(name: string): string;
  fullName(): string;
}

class Player implements User {
  constructor(public firstName: string, public lastName: string) {}
  sayHi(name: string) {
    return `Hello ${name}.`;
  }
  fullName() {
    return `${this.firstName} ${this.lastName}`;
  }
}

javascript로 빌드 시 code

class Player {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
  sayHi(name) {
    return `Hello ${name}.`;
  }
  fullName() {
    return `${this.firstName} ${this.lastName}`;
  }
}