본문 바로가기
TypeScript

[타입스크립트] 인터페이스란? (인터페이스와 클래스의 차이점)

by 메이플 🍁 2022. 11. 17.

인터페이스란?

오브젝트의 타입을 설정하는 일종의 오브젝트 설계도

+ 추상화 클래스와 같이 표준화된 프로퍼티와 메서드를 갖도록하는 설계도

 

추상화 클래스 vs 인터페이스

  • 공통점: 클래스의 모양을 결정할 수 있다 (클래스의 프로퍼티와 메서드를 지정)
  • 클래스: 추상화 클래스는 자바스크립트로 변환되며 추상화 클래스를 상속받은 클래스의 프로퍼티와 메소드에 private, protected, public를 지정할 수 있다
  • 인터페이스: 인터페이스는 자바스크립트로 변환되지 않아 파일이 가벼워지며 인터페이스를 상속받은 클래스의 프로퍼티와 메소드에는 public만 지정할 수 있다

추상화 클래스 예제

클래스 Player에서는 User의 모든 메서드를 구현해야한다.

abstract class User {
  constructor(
    protected firstName: string,
    protected lastName: string
  ){}
  abstract sayHi(name:string):string
  abstract fullName():string
}

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

추상화 클래스의 특징

1. 인스턴스를 만들 수 없음

const user = new User // 에러 발생

2. 추상화 클래스는 자바스크립트에서 일반 클래스로 변환된다

abstract class User {
  ...
}

인터페이스 예제

인터페이스가 하는 일

  • 오브젝트 모양 묘사
  • 클래스의 모양 묘사

인터페이스를 추상화 클래스 대신 사용할때

  • 인터페이스의 장점: 자바스크립트로 변환되지 않아 파일이 가벼워짐
  • 인터페이스의 단점: private property를 사용할 수 없다
interface User {
  firstName: string,
  lastName: string,
  sayHi(name:string):string
  fullName():string
}

interface Human {
  health: number
}

class Player implements User, Human { // 여러 인터페이스를 상속받을 수 있다
  constructor(
    public firstName: string, // 인터페이스를 상속한 프로퍼티는 항상 public이어야 한다
    public lastName:string,
    public health:number
  ){}
  fullName() {
    return `${this.firstName} ${this.lastName}`
  }
  sayHi(name:string) {
    return `Hello ${name}. My Name is ${this.fullName()}`
  }
}

댓글