Skip to content

Commit 85864ce

Browse files
committed
🚩: generic과 interface를 활용한 개념
1 parent 5841422 commit 85864ce

File tree

2 files changed

+30
-21
lines changed

2 files changed

+30
-21
lines changed

src/index.ts

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

3-
// union이 아닌 제네릭 <T>사용하기
4-
// 여기서 T는 임의의 타입을 나타내는 변수이다. 제네릭 함수가 호출될 때 T는 실제 타입으로 대체된다.
5-
//따라서 이 함수에서 T는 배열(T[])의 요소 타입을 나타내며 호출 시점에 이 타입이 구체적으로 결정된다.
4+
import { Mobile } from "./utils/data.interface";
65

7-
function getSize<T>(arr: T[]): number {
8-
return arr.length;
9-
}
6+
const m1: Mobile<object> = {
7+
name: "s21",
8+
price: 1000,
9+
option: {
10+
color: "red",
11+
coupon: false,
12+
}
13+
};
1014

11-
// number Type
12-
// number로 지정된 타입을 사용할 수도 있지만 유니온을 사용해서 여러 타입을 지정 할수도 있다.
13-
const arr1 = [1, 2, '3'];
14-
getSize<number | string>(arr1);
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+
};
1524

16-
// string Type
17-
const arr2 = ["a", "b", "c"];
18-
getSize<string>(arr2);
19-
20-
// boolean Type
21-
const arr3 = [false, true, true];
22-
getSize<boolean>(arr3);
23-
24-
// object Type
25-
const arr4 = [{}, {}, { name: 'Time' }];
26-
getSize<object>(arr4);
25+
const m2: Mobile<string> = {
26+
name: "s20",
27+
price: 900,
28+
option: "good",
29+
};

src/utils/data.interface.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,4 +74,10 @@ export interface InterToy {
7474
name: string;
7575
color: string;
7676
price: number;
77+
}
78+
79+
export interface Mobile<T> {
80+
name: string;
81+
price: number;
82+
option: T;
7783
}

0 commit comments

Comments
 (0)