Interfaces#
속성 이름과 객체의 값의 type을 나타내는 새로운 type을 만드는 것
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| // 너무 긴 annotation
const oldCivic = {
name: 'civic',
year: 2000,
broken: true,
};
const printVehicle = (vehicle: {
name: string;
year: number;
broken: boolean;
}): void => {
console.log(`Name: ${vehicle.name}`);
console.log(`Year: ${vehicle.year}`);
console.log(`Broken? ${vehicle.broken}`);
};
printVehicle(oldCivic);
|
인터페이스를 통해 간편하게 할 수 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
| interface Vehicle {
name: string;
year: Date; // 모든 type을 interface내의 속성 type으로 설정 가능
broken: boolean;
summary(): string; // 함수도 설정 가능
}
const oldCivic = {
name: 'civic',
year: new Date(),
broken: true,
summary(): string {
return `Name: ${this.name}`; // interface에 적힌대로 함수도 설정해야함.
},
};
const printVehicle = (vehicle: Vehicle): void => {
// 짧아졌다!
console.log(`Name: ${vehicle.name}`);
console.log(`Year: ${vehicle.year}`);
console.log(`Broken? ${vehicle.broken}`);
console.log(vehicle.summary());
};
printVehicle(oldCivic); //oldCivic이 Vehicle 인터페이스와 속성의 이름이나 type이 다르면 오류가 발생한다.
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| interface Vehicle {
summary(): string;
}
const oldCivic = {
name: 'civic',
year: new Date(),
broken: true,
summary(): string {
return `Name: ${this.name}`;
},
};
const printVehicle = (vehicle: Vehicle): void => {
console.log(vehicle.summary());
};
printVehicle(oldCivic);
|
인터페이스를 위와 같이 수정해도 오류가 감지되지 않는다.
TS는 인터페이스에서 정의된 속성인 summary가 존재하는지만 신경쓰기 때문이다. 그 이외의 것은 상관하지 않는다. 위의 Vehicle이 논리적으로 말이 안되는 것은 TS가 잡아낼 오류가 아니다. Summary만 있는게 Vehicle과는 상관없으니까 이름을 바꿔야겠지만, 그건 우리가 해야할 일이라는 뜻!
코드 재사용성#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
| // 3) 인터페이스에서 코드 재사용성 높이기
interface Reportable {
summary(): string;
}
const oldCivic = {
name: 'civic',
year: new Date(),
broken: true,
summary(): string {
return `Name: $[this.name]`;
},
};
const drink = {
color: 'brown',
carbonated: true,
sugar: 40,
summary(): string {
return `My drink has ${this.sugar} grams of sugar`;
},
};
const printSummary = (item: Reportable): void => {
console.log(item.summary());
};
printSummary(oldCivic); // oldCivic은 summary가 올바른 속성으로 존재하기 때문에 Reportable type이다. 따라서 변수로 사용 가능
printSummary(drink); // drink도 summary가 올바른 속성으로 존재하기 때문에 Reportable type이다. 따라서 변수로 사용 가능
|
oldCivic과 drink는 다른 속성들을 지녔지만 둘다 Reportable이 type이라 printSummary 함수의 변수로 사용 가능하다.
매우 다른 다수의 object를 위해 하나의 단일 인터페이스를 사용할 수 있다!