타입스크립트의 인터페이스는 클래스의 설계도 역할을 할 수 있다.
다음과 같이 인터페이스를 이용해 클래스에 어떤 필드들이 존재하고, 어떤 메서드가 존재하는지 정의할 수 있다.
interface CharacterInterface {
name: string;
moveSpeed: number;
move(): void;
}
class Character implements CharacterInterface {
constructor(
public name: string,
public moveSpeed: number,
) {}
move(): void {
console.log(`${this.moveSpeed} 속도로 이동!`);
}
}

인터페이스 CharacterInterface는 name, moveSpeed 프로퍼티와 move 메서드를 갖는 객체 타입을 정의한다.Character 클래스는 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} 속도로 이동!`);
}
}
위 코드에서 extra 필드는 인터페이스에 정의되어 있지 않지만, 클래스에서 추가로 정의하며 사용할 수 있다.
인터페이스는 클래스가 반드시 가져야 할 최소한의 구조만 강제할 뿐, 추가 속성을 막지는 않는다.
'TIL' 카테고리의 다른 글
| [CS50] 컴퓨팅 사고 - 2진법 (0) | 2025.11.03 |
|---|---|
| [TS] 클래스와 접근제어자 사용 연습 (0) | 2025.11.03 |
| [TS] 접근 제어자 (0) | 2025.11.01 |
| [TS] 클래스 (0) | 2025.11.01 |
| [TS] 인터페이스 선언 합침 (0) | 2025.11.01 |
