TypeScript에서 클래스가 특정 Interface의 계약을 준수하도록 강제하는 키워드
// 인터페이스 정의
interface Vehicle {
start(): void;
stop(): void;
speed: number;
}
// 인터페이스 구현
class Car implements Vehicle {
// 반드시 구현
speed: number = 0;
// 반드시 구현
start() {
console.log("Car started");
}
// 반드시 구현
stop() {
console.log("Car stopped");
}
}
이러한 implements 키워드는 여러 Interface 구현이 가능하다.
interface Lockable {
lock(): void;
unlock(): void;
}
interface Chargeable {
charge(): void;
}
class ElectricCar implements Vehicle, Lockable, Chargeable {
speed: number = 0;
start() { }
stop() { }
lock() { }
unlock() { }
charge() { }
}
하지만 특정 Interface의 계약을 준수하도록 강제하는 키워드이기 때문에 아래와 같은 코드는 에러가 발생한다.
class InvalidCar implements Vehicle {
// Error: 'start' 메서드가 없음
// Error: 'stop' 메서드가 없음
// Error: 'speed' 속성이 없음
constructor() {}
}
class PartialCar implements Vehicle {
speed = 0;
start() {}
// Error: 'stop' 메서드가 없음
}
implements는 특히 대규모 어플리케이션에서 타입 안정성과 코드 품질을 높이는데 유용한 도구이다.