interface Mailable {
send(email: string, after: number): boolean
queue(email: string): boolean
}
위의 Mailable
이라는 인터페이스가 2개의 메소드를 가지고 있고, 이 인터페이스를 사용한 클래스가 있을때 인터페이스에 아래와 같은 새 메소드를 추가하려하면 문제가 있음.
later(email: string, after: number): void
문제를 해결하기 위해서 이미 있는 Mailable
인터페이스를 확장한 새 인터페이스를 만들어야함.
interface FutureMailable extends Mailable {
later(email: string, after: number): boolean
}
인터페이스를 extend 하려면 extends
키워드를 사용하면됨.
interface A {
a(): void
}
interface B extends A {
b(): void
}
위에서 인터페이스 B
는 인터페이스 A
를 해서 method a()
와 b()
를 가지게 됨.
아래는 FutureMailable
인터페이스를 적용한 예임.
class Mail implements FutureMailable {
later(email: string, after: number): boolean {
console.log(`Send email to ${email} in ${after} ms.`);
return true;
}
send(email: string, after: number): boolean {
console.log(`Sent email to ${email} after ${after} ms. `);
return true;
}
queue(email: string): boolean {
console.log(`Queue an email to ${email}.`);
return true;
}
}
인터페이스는 여러개의 인터페이스를 상속받을 수 있음.
interface C {
c(): void
}
interface D extends B, C {
d(): void
}
위에서 인터페이스 D
는 인터페이스 B
와 C
를 상속받아서 a()
, b()
, c()
, d()
메소드를 모두 가지고 있음.
타입스크립트는 인터페이스가 클래스를 extend하게 해줌. 이경우에 인터페이스는 클래스의 모든 property와 메소드를 상속받게 됨. 이때 public 멤버들만이 아닌 private과 protected 멤버들도 상속받음.
이 말은 인터페이스가 private이나 protected 멤버가 있는 클래스를 상속했을때 이 인터페이스는 상속한 클래스 혹은 상속한 클래스의 서브클래스에서만 적용가능하다는 뜻임.
이렇게 하면, 인터페이스의 사용처를 인터페이스가 상속한 해당 클래스 혹은 그 클래스의 서브클래스만 사용가능하게 제한랄 수 있음.
class Control {
private state: boolean;
}
interface StatefulControl extends Control {
enable(): void
}
class Button extends Control implements StatefulControl {
enable() { }
}
class TextBox extends Control implements StatefulControl {
enable() { }
}
class Label extends Control { }
// 인터페이스가 상속하지 않은 클래스에서 인터페이스를 사용하려하면 에러가나옴
// Error: cannot implement
class Chart implements StatefulControl {
enable() { }
}
- 인터페이스는 하나 이상의 인터페이스를 extend 가능함
- 인터페이스는 클래스도 extend할 수 있음. 클래스가 private이나 protected 멤버를 가지고 있을 경우에 해당 클래스 혹은 해당 클래스의 서브클래스만 인터페이스를 사용할 수 있음