1
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์ผ๋ก ํ์
์ด ๋ฐํ ๋ ๊ฒ์ด๋ค.
4
-
5
- function printResult ( num : number | string | undefined ) : void {
6
- if ( typeof num === 'number' || typeof num === 'string' ) {
7
- console . log ( 'Result: ' , + num ) ;
8
- } else {
9
- console . log ( 'this is Undefined!' ) ;
10
- }
11
- } //์ผ๋ฐ์ ์ผ๋ก ํจ์์ ๋ฐํ ํ์
์ ์ ํ์ง ์์ผ๋ฉด void๋ก ํ๋จํ๋ค. `:void`๋ฅผ ๋ช
์ํ์ง ์์๋ ํด๋น ํจ์์ ๋ง์ฐ์ค๋ฅผ ํธ๋ฒํ๋ฉด void๋ก ํ๋ณ ๋์ด ์๋ ๊ฒ์ ํ์ธ ํ ์ ์๋ค. ๋ฐ๋ผ์ ๊ตณ์ด void๋ฅผ ๋ช
์ํ ํ์๋ ์๋ค.
12
-
13
- //๋ฐํ๋์ง ์๋ ํจ์๋ฅผ ๊ธฐ์ค์ผ๋ก log๋ก ํ์ธ์ ํด๋ณด๋ฉด ์ด๋ค ๊ฒฐ๊ณผ๊ฐ ๋์ฌ๊น
14
- console . log ( printResult ( add ( 5 , 12 ) ) ) ; //๊ฒฐ๊ณผ์ ์ผ๋ก `undefined`๋ผ๋ ๊ฒฐ๊ณผ๊ฐ ๋์จ๋ค. ๋ฐํ๋ ๊ฐ์ด ์๊ธฐ ๋๋ฌธ์ ์ ์๋์ง ์์ ๋ฐ์ค๋ง ์ถ๋ ฅ์ด ๋๋ ๊ฒ์ด๋ค. ์ฐธ๊ณ ๋ก `undefined`๋ ๊ฐ์ด ์๋๊ฒ ์๋๋ผ ๊ฐ์ ๋ด์๋ด๊ณ ์๋ ๋ฐ์ค์ ์๋ฌด๊ฒ๋ ๋ด๊ฒจ ์์ง ์๋ค๋ ์๋ฏธ์ `๊ฐ`์ด๋ค. ์ฆ, ๋น์ด ์๋ ๋ฐ์ค๋ฅผ ์ถ๋ ฅํ ๊ฒ์ด๋ค.
15
-
16
- let UndefinedValue : undefined ; //๋ณ์๋ก undefined๋ผ๋ ํ์
์ ์ง์ ํ ์๋ ์๋ค. ํ์ง๋ง ํจ์์์๋ undefined๋ผ๋ ํ์
์ ํ ๋น ํ๋ฉด ์๋๋ค. ๋ฐํ๊ฐ์ด ์๋ ํจ์๋ฅผ ์ถ๋ ฅํ๋ฉด undefined๊ฐ ์ถ๋ ฅ๋๋๋ฐ ์ด๋ ํจ์์ ํ์ฉ๊ณผ ์๋ฏธ๊ฐ ์์คํ๊ฒ ๋๋ค.
2
+ return n1 + n2 ;
3
+ }
17
4
18
- function UndefinedFunction ( value : string ) : undefined {
19
- console . log ( value ) ;
20
- // return value; //error ts(2322) -> 'string' ํ์์ 'undefined' ํ์์ ํ ๋นํ ์ ์์ต๋๋ค
21
- return ; //๊ฒฐ๊ณผ์ ์ผ๋ก ํจ์์ ์๋ฌด๊ฒ๋ ์๋ return์ด์ฌ์ผ undefined๊ฐ ๋๋ค.
5
+ function printResult ( num : number ) : void {
6
+ console . log ( 'Result: ' , + num ) ;
22
7
}
23
8
24
- printResult ( UndefinedFunction ( 'test' ) ) ;
9
+ printResult ( add ( 1 , 2 ) ) ;
10
+
11
+ // let result: Function; //์ผ๋ฐ์ ์ธ ๋ฐฉ์์ผ๋ก ํจ์ ํ์
์ ํ ๋นํ ๊ฒฝ์ฐ
12
+ let result : ( a : number , b : number ) => number ; // ํ์ดํ๊ธฐ๋ก ํจ์์ ๋ฐํ ๊ฐ๊น์ง ํ ๋นํ ๊ฒฝ์ฐ
13
+ result = add ;
14
+ //result = printResult; // error ts(2322) -> 'void' ํ์์ 'number' ํ์์ ํ ๋นํ ์ ์์ต๋๋ค.
15
+ // ํด๋น ์ค๋ฅ๋ result์ ํ์
์ number๋ก ๋ฐํ๋๋ ํจ์์ฌ์ผ๋ง ๊ฐ๋ฅํ๊ธฐ ๋๋ฌธ์ด๋ค. ์ฆ, printResult๋ void๊ฐ ๋ฐํ์ด๊ธฐ ๋๋ฌธ์ ์ค๋ฅ๊ฐ ๋ฐ์ํ๋ค.
16
+ // result = 0; //๊ฐ์ด ์ฌํ ๋น ๋๋ฉด์ 0์ผ๋ก ๊ฐ์ด ์ถ๋ ฅ๋๋ค.
17
+ console . log ( result ( 1 , 2 ) ) ; // ๊ทธ๋ ๋ค๋ฉด result ๋ณ์์ ํจ์ ํ์
์ ์ง์ ํ๋ฉด ๋์ง ์์๊น?
0 commit comments