타입스크립트의 인터페이스는 클래스의 설계도 역할을 할 수 있다.
다음과 같이 인터페이스를 이용해 클래스에 어떤 필드들이 존재하고, 어떤 메서드가 존재하는지 정의할 수 있다.
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} 속도로 이동!`);
}
}
인터페이스 CharacterInterface
는 name, moveSpeed
프로퍼티와 move
메서드를 갖는 객체 타입을 정의한다.
그런데 이 인터페이스를 클래스에서 implements
키워드와 함께 사용하면 이제부터 이 클래스가 생성하는 객체는 모두 이 인터페이스 타입을 만족하도록 클래스를 구현해야 한다.
private
나 protected
필드가 필요하다면 아래와 같이 따로 정의해주어야 한다.
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} 속도로 이동!`);
}
}