1
- const person : {
2
- name : string ,
3
- age : number ,
4
- hobbies : string [ ] ;
5
- role : ( number | string ) [ ] ;
6
- } = {
7
- name : 'Maximilian' ,
8
- age : 30 ,
9
- hobbies : [ 'Sports' , 'Cooking' ] ,
10
- role : [ 2 , 'author' ]
11
- } ;
1
+ function combine ( n1 : number | string , n2 : number | string ) {
2
+ let result ;
3
+ if ( typeof n1 === 'number' && typeof n2 === 'number' ) {
4
+ result = n1 + n2 ;
5
+ } else if ( typeof n1 === 'string' && typeof n2 === 'string' ) {
6
+ result = n1 + n2 ;
7
+ } else {
8
+ result = n1 . toString ( ) + n2 . toString ( ) ;
9
+ } // ํด๊ฒฐ ๋ฐฉ๋ฒ: if๋ฌธ์ผ๋ก typeof๋ก ๊ฐ ํ์
๋ค์ด ๋ฌด์์ธ์ง ์๋ณํ ํ ์ฐ์ฐ์ ์ ์ฉํ๋ค. ์ฐ์ฐ์ด ์ ์ฉ๋์ง ์๋ ํ์
๋ค์ ๋ชจ๋ string์ผ๋ก ํ๋ณํ ํ ์ฐ์ฐ์ ์์ผ์ฃผ๋ฉด ๋๋ค. ๋ฐ๋ผ์ ์ ๋์จ ํ์
์ผ๋ก ์ฌ๋ฌ ํ์
์ ์ ์ฐํ๊ฒ ์ฌ์ฉํ ์ ์์ง๋ง ์ด๊ฒ๋ค์ ํ์ฉํ ๋๋ ์ ํํ ์ด๋ค ํ์
์ ๋ฐ๋์ง์ ๊ดํ ๋ก์ง์ด ๋ณดํต ํจ์๋ ํด๋์ค ๊ตฌ์กฐ์ ๋ง์ด ํ์ํ๋ค.
10
+ return result ;
11
+ }
12
+ // Ts๊ฐ ์ผ๋ คํ๋ error์ ๊ทผ์์ ์๋์ ๊ฐ๋ค.
13
+ // const b1: boolean = true;
14
+ // const b2: boolean = false;
15
+ // console.log(b1 + b2);
12
16
13
- person . role . push ( 'admin' ) ;
14
- person . role [ 1 ] = 10 ;
15
- person . role = [ 0 , 'admin' , 'user' ] ;
17
+ const CombineAges = combine ( 20 , 30 ) ;
18
+ console . log ( CombineAges ) ;
16
19
17
- //any๋ ์ด๋ค ํ์
์ด๋ ํ์ฉํ๋ ํ์
์ด๋ค. ์ด๋ป๊ฒ ๋ณด๋ฉด ์ ์ฐํ๋ค๊ณ ๋๊ปด์ง์ง์ง ๋ชจ๋ฅด๊ฒ ์ง๋ง ํ์
์คํฌ๋ฆฝํธ์ ์ฅ์ ์ ์ ํ ํ์ฉํ์ง ๋ชปํ๊ธฐ์ ์ข์ ๋ฐฉ๋ฒ์ ์๋๋ค.
18
- let favoriteActivities : any [ ] ;
19
- favoriteActivities = [ 'Sports' , 1 ] ; //์ด๋ ๊ฒ ๋ฐฐ์ด์ ๋ง๊ตฌ์ก์ด๋ก ์๋ก ๋ค๋ฅธ ํ์
์ ๋ฃ์ด๋ ์๋ฌด๋ฐ ์๋ฌ๊ฐ ์ผ์ด๋์ง ์๋๋ค.
20
-
21
- console . log ( person . name ) ;
22
-
23
- for ( const hobby of person . hobbies ) {
24
- console . log ( hobby ) ;
25
- }
20
+ const CombineNames = combine ( 'Max' , 'Anna' ) ;
21
+ console . log ( CombineNames ) ;
0 commit comments