File tree Expand file tree Collapse file tree 2 files changed +30
-21
lines changed Expand file tree Collapse file tree 2 files changed +30
-21
lines changed Original file line number Diff line number Diff line change 1
1
// Generic : 클래스나 타입을 재사용하기 위한 문법
2
+ // interface와 Generic을 사용해서 활용할 수도 있다.
2
3
3
- // union이 아닌 제네릭 <T>사용하기
4
- // 여기서 T는 임의의 타입을 나타내는 변수이다. 제네릭 함수가 호출될 때 T는 실제 타입으로 대체된다.
5
- //따라서 이 함수에서 T는 배열(T[])의 요소 타입을 나타내며 호출 시점에 이 타입이 구체적으로 결정된다.
4
+ import { Mobile } from "./utils/data.interface" ;
6
5
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
+ } ;
10
14
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
+ } ;
15
24
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
+ } ;
Original file line number Diff line number Diff line change @@ -74,4 +74,10 @@ export interface InterToy {
74
74
name : string ;
75
75
color : string ;
76
76
price : number ;
77
+ }
78
+
79
+ export interface Mobile < T > {
80
+ name : string ;
81
+ price : number ;
82
+ option : T ;
77
83
}
You can’t perform that action at this time.
0 commit comments