interface에서는 public, private 사용할 수 없지만, readonly는 사용할 수 있습니다.
interface Greetable {
readonly name: string;
greet(phrase: string): void;
}
// 아래 코드 처럼 implements 여러개의 Interface 추가 가능
// class Person implements Greetable, AnotherInterface {}
class Person implements Greetable {
name: string;
age = 30;
constructor(n: string){
this.name = n;
}
greet(phrase: string) {
console.log(phrase + " " + this.name);
}
}
let user1: Greetable;
user1 = new Person("max");
// user1.name = "mana"; new Person("max")를 통해 "max"가 설정된 상태라 "mana"를 추가할 수 없습니다.
console.log(user1);
// Person {age: 30, name: "max");
class Person implements를 통해 여러개의 interface를 설정할 수 있지만 비효율적입니다.
이런 경우 Greetable extends Named를 통해 interface를 확장하고 class Person에 implements Greetable만 적어줍니다.
ex) interface 확장 전
interface Named {
readonly name: string;
}
interface Greetable {
greet(phrase: string): void;
}
class Person implements Greetable, Named {
name: string;
age = 30;
constructor(n: string){
this.name = n;
}
greet(phrase: string) {
console.log(phrase + " " + this.name);
}
}
ex) interface 확장 사용
interface Named {
readonly name: string;
}
interface Greetable extends Named {
greet(phrase: string): void;
}
// Greetable에서 interface를 확장했을 때 Greetable에 name이 추가된 상태이기 때문에, class Person 내 name: string설정해야 합니다.
class Person implements Greetable {
name: string;
age = 30;
constructor(n: string){
this.name = n;
}
greet(phrase: string) {
}
}
class 상속을 사용하는 경우 하나의 class만 상속할 수 있고, 다수의 class로 부터 상속할 수 없습니다. 하지만 interface는 여러 개 확장할 수 있죠.
//type AddFunction = (a: number, b: number) => number;
interface AddFunction {
(a: number, b: number): number;
}
let add: AddFunction;
// add: AddFunction이기 때문에 아래 n1: number를 string으로 바꿀 경우 작동하지 않는다.
add = (n1: number, n2: number) => {
return n1 + n2;
};
interface Named {
readonly name: string;
}
interface Greetable extends Named {
greet(phrase: string): void;
}
// Greetable에서 interface를 확장했을 때 Greetable에 name이 추가된 상태이기 때문에, class Person 내 name: string설정해야 합니다.
class Person implements Greetable {
name: string;
age = 30;
constructor(n: string){
this.name = n;
}
greet(phrase: string) {
}
}