인터페이스와 클래스

woodstock·2024년 1월 29일
0
post-thumbnail

인터페이스를 구현하는 클래스

타입스크립트의 인터페이스는 클래스의 설계도 역할을 할 수 있다.

다음과 같이 인터페이스를 이용해 클래스에 어떤 필드들이 존재하고, 어떤 메서드가 존재하는지 정의할 수 있다.

interface CharacterInterface {
  name: string;
  moveSpeed: number;
  move(): void;
}

class Character implements CharacterInterface {
  constructor(
    public name: string,
    public moveSpeed: number,
    private extra: string
  ) {}

  move(): void {
    console.log(`${this.moveSpeed} 속도로 이동!`);
  }
}

인터페이스 CharacterInterfacename, moveSpeed 프로퍼티와 move 메서드를 갖는 객체 타입을 정의한다.

그런데 이 인터페이스를 클래스에서 implements 키워드와 함께 사용하면 이제부터 이 클래스가 생성하는 객체는 모두 이 인터페이스 타입을 만족하도록 클래스를 구현해야 한다.

privateprotected필드가 필요하다면 아래와 같이 따로 정의해주어야 한다.

interface CharacterInterface {
  name: string;
  moveSpeed: number;
  move(): void;
}

class Character implements CharacterInterface {
  constructor(
    public name: string,
    public moveSpeed: number,
    private extra: string // 추가로 정의하는 것은 가능
  ) {}

  move(): void {
    console.log(`${this.moveSpeed} 속도로 이동!`);
  }
}
profile
해내는 사람

0개의 댓글