Skip to content

Commit 6dba5b0

Browse files
committed
🚩: generic과 interface를 extends로 활용
1 parent 85864ce commit 6dba5b0

File tree

2 files changed

+25
-23
lines changed

2 files changed

+25
-23
lines changed

src/index.ts

Lines changed: 11 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,17 @@
11
// Generic : 클래스나 타입을 재사용하기 위한 문법
22
// interface와 Generic을 사용해서 활용할 수도 있다.
33

4-
import { Mobile } from "./utils/data.interface";
4+
import { myUser, myCar, myBook } from "./utils/data.interface";
55

6-
const m1: Mobile<object> = {
7-
name: "s21",
8-
price: 1000,
9-
option: {
10-
color: "red",
11-
coupon: false,
12-
}
13-
};
6+
const user: myUser = { name: "a", age: 10 };
7+
const car: myCar = { name: "bmw", color: "red" };
8+
const book: myBook = { price: 3000 };
149

15-
// object의 타입이 지정이 되어 있다면 아래와 같이 사용하면 된다.
16-
const m11: Mobile<{ color: string; coupon: boolean }> = {
17-
name: "s21",
18-
price: 1000,
19-
option: {
20-
color: "red",
21-
coupon: false,
22-
}
23-
};
10+
// 제네릭 T를 사용해보면 T가 name 속성을 가지고 있다는 보장이 없기 때문에 error가 뜬다. 따라서 name의 타입을 extends를 사용해서 확장 시키면 error가 사라진다.
11+
function showName<T extends { name: string }>(data: T): string {
12+
return data.name;
13+
}
2414

25-
const m2: Mobile<string> = {
26-
name: "s20",
27-
price: 900,
28-
option: "good",
29-
};
15+
showName(user);
16+
showName(car);
17+
//showName(book); //error -> book은 name 객체가 없기 때문에 error가 발생한다. 이를 해결하기 위해서는 조건을 통해서 유연하게 대체를 할수 있다.

src/utils/data.interface.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,4 +80,18 @@ export interface Mobile<T> {
8080
name: string;
8181
price: number;
8282
option: T;
83+
}
84+
85+
export interface myUser {
86+
name: string;
87+
age: number;
88+
}
89+
90+
export interface myCar {
91+
name: string;
92+
color: string;
93+
}
94+
95+
export interface myBook {
96+
price: number;
8397
}

0 commit comments

Comments
 (0)