👶 TypeScript

인터페이스 구현

개발자 린다씨 2023. 1. 15. 16:00
반응형

구현

클래스를 선언할 때 implements라는 키워드를 이용해 특정 인터페이스를 만족 시킴을 표현할 수 있습니다.

 

다른 명시적인 타입 어노테이션처럼 implements로 타입 수준의 제한을 추가하면 구현에 문제가 있을 때 어디가 잘못되었는지 쉽게 파악할 수 있습니다.

 

또한 어댑터(adapter), 팩토리(factory), 전략(strategy) 등 흔한 디자인 패턴을 구현하는 대표적인 방식이기도 합니다.

 

implements는 아래처럼 사용할 수 있습니다.

interface Animal {
  eat(food: string): void
  sleep(hours: number): void
}

class Dog implements Animal {
  eat(food: string){
    console.info('Ate some', food, 'food')
  }
  sleep(hours: number): void {
    console.info('Slept for', hours, 'hours')
  }
}

Dog는 Animal이 선언하는 모든 메서드를 구현해야 하며, 필요하다면 메서드나 프로퍼티를 추가로 구현할 수 있습니다.

 

인터페이스로 인스턴스 프로퍼티를 정의할 수 있지만 가시성 한정자(private, protected, public)는 선언할 수 없으며 static 키워드도 사용할 수 없습니다.

 

객체 안의 객체 타입처럼 인스턴스 프로퍼티를 readonly로 설정할 수 있습니다.

interface Animal {
  readonly name: string
  eat(food: string): void
  sleep(hours: number): void
}

한 클래스가 하나의 인터페이스만 구현할 수 있는 것은 아니며 필요하면 여러 인터페이스를 구현할 수 있습니다.

interface Animal {
  readonly name: string
  eat(food: string): void
  sleep(hours: number): void
}

interface Canidae {
  bark(): void
}

class Dog implements Animal, Canidae {
  name = 'Whisky'
  eat(food: string){
    console.info('Ate some', food, 'food')
  }
  sleep(hours: number){
    console.info('Slept for', hours, 'hours')
  }
  bark(){
    console.info('Wa U Wa U')
  }
}

이 모든 기능은 완전한 타입 안전성을 제공합니다. 프로퍼티를 빼먹거나 구현에 문제가 있으면 TypeScript가 바로 지적해 줍니다.

반응형