1
- //ํญ์ ์ ๋์จ ํ์
์ ์ง์ ํ๋ ๊ฒ์ ๋ง์ด ๋ฒ๊ฑฐ๋กญ๋ค. ์ด์ alias ํ์
์ผ๋ก ์ฌ์ฉ์ ์ง์ ํ์
์ ์ ํ ์ ์๋ค. ์ฆ, ํ์
์ ์ฐ๋ฆฌ๊ฐ ๋ค๋ก ๋ณ์นญ์ผ๋ก ๋ง๋ค์ด ๋ผ ์ ์๋ค.
1
+ function add ( n1 : number , n2 : number ) : number {
2
+ return n1 + n2 ; //error ts(2322) 'number' ํ์์ 'string' ํ์์ ํ ๋นํ ์ ์์ต๋๋ค.
3
+ } //ํ์ฌ return์ ์ ์ํ n1+n2๋ก ์ธํด์ addํจ์์ ๋ฐํ ํ์
์ Number์ด๋ค. ๋ง์ฝ toSting์ผ๋ก ํ๋ณํ์ ํ `n1.toString() + n2.toString()`์ผ ๊ฒฝ์ฐ ๋ฐํ๋ ๊ฐ์ string์ผ๋ก ํ์
์ด ๋ฐํ ๋ ๊ฒ์ด๋ค.
2
4
3
- type Combinable = number | string ;
4
- type ConversionCustom = 'as-number' | 'as-text' ;
5
-
6
- function combine (
7
- n1 : Combinable ,
8
- n2 : Combinable ,
9
- resultConversion : ConversionCustom ,
10
- ) {
11
- let result ;
12
- if ( typeof n1 === 'number' && typeof n2 === 'number' || resultConversion === 'as-number' ) {
13
- result = + n1 + + n2 ;
14
- } else if ( typeof n1 === 'string' && typeof n2 === 'string' ) {
15
- result = n1 + n2 ;
5
+ function printResult ( num : number | string | undefined ) : void {
6
+ if ( typeof num === 'number' || typeof num === 'string' ) {
7
+ console . log ( 'Result: ' , + num ) ;
16
8
} else {
17
- result = n1 . toString ( ) + n2 . toString ( ) ;
9
+ console . log ( 'this is Undefined!' ) ;
18
10
}
19
- // if (resultConversion === 'as-number') {
20
- // return +result;
21
- // } else {
22
- // return result.toString();
23
- // }
24
- }
11
+ } //์ผ๋ฐ์ ์ผ๋ก ํจ์์ ๋ฐํ ํ์
์ ์ ํ์ง ์์ผ๋ฉด void๋ก ํ๋จํ๋ค. `:void`๋ฅผ ๋ช
์ํ์ง ์์๋ ํด๋น ํจ์์ ๋ง์ฐ์ค๋ฅผ ํธ๋ฒํ๋ฉด void๋ก ํ๋ณ ๋์ด ์๋ ๊ฒ์ ํ์ธ ํ ์ ์๋ค. ๋ฐ๋ผ์ ๊ตณ์ด void๋ฅผ ๋ช
์ํ ํ์๋ ์๋ค.
25
12
26
- const combineAges = combine ( 20 , 30 , 'as-number' ) ;
27
- console . log ( combineAges ) ;
13
+ //๋ฐํ๋์ง ์๋ ํจ์๋ฅผ ๊ธฐ์ค์ผ๋ก log๋ก ํ์ธ์ ํด๋ณด๋ฉด ์ด๋ค ๊ฒฐ๊ณผ๊ฐ ๋์ฌ๊น
14
+ console . log ( printResult ( add ( 5 , 12 ) ) ) ; //๊ฒฐ๊ณผ์ ์ผ๋ก `undefined`๋ผ๋ ๊ฒฐ๊ณผ๊ฐ ๋์จ๋ค. ๋ฐํ๋ ๊ฐ์ด ์๊ธฐ ๋๋ฌธ์ ์ ์๋์ง ์์ ๋ฐ์ค๋ง ์ถ๋ ฅ์ด ๋๋ ๊ฒ์ด๋ค. ์ฐธ๊ณ ๋ก `undefined`๋ ๊ฐ์ด ์๋๊ฒ ์๋๋ผ ๊ฐ์ ๋ด์๋ด๊ณ ์๋ ๋ฐ์ค์ ์๋ฌด๊ฒ๋ ๋ด๊ฒจ ์์ง ์๋ค๋ ์๋ฏธ์ `๊ฐ`์ด๋ค. ์ฆ, ๋น์ด ์๋ ๋ฐ์ค๋ฅผ ์ถ๋ ฅํ ๊ฒ์ด๋ค.
28
15
29
- const combinedStringAges = combine ( '20' , '30' , 'as-number' ) ;
30
- console . log ( combinedStringAges ) ;
16
+ let UndefinedValue : undefined ; //๋ณ์๋ก undefined๋ผ๋ ํ์
์ ์ง์ ํ ์๋ ์๋ค. ํ์ง๋ง ํจ์์์๋ undefined๋ผ๋ ํ์
์ ํ ๋น ํ๋ฉด ์๋๋ค. ๋ฐํ๊ฐ์ด ์๋ ํจ์๋ฅผ ์ถ๋ ฅํ๋ฉด undefined๊ฐ ์ถ๋ ฅ๋๋๋ฐ ์ด๋ ํจ์์ ํ์ฉ๊ณผ ์๋ฏธ๊ฐ ์์คํ๊ฒ ๋๋ค.
17
+
18
+ function UndefinedFunction ( value : string ) : undefined {
19
+ console . log ( value ) ;
20
+ // return value; //error ts(2322) -> 'string' ํ์์ 'undefined' ํ์์ ํ ๋นํ ์ ์์ต๋๋ค
21
+ return ; //๊ฒฐ๊ณผ์ ์ผ๋ก ํจ์์ ์๋ฌด๊ฒ๋ ์๋ return์ด์ฌ์ผ undefined๊ฐ ๋๋ค.
22
+ }
31
23
32
- const combineNames = combine ( 'Max' , 'Anna' , 'as-text' ) ;
33
- console . log ( combineNames ) ;
24
+ printResult ( UndefinedFunction ( 'test' ) ) ;
0 commit comments