|
1 |
| -function combine(n1: number | string, n2: number | string) { |
| 1 | +function combine( |
| 2 | + n1: number | string, |
| 3 | + n2: number | string, |
| 4 | + resultConversion: 'as-number' | 'as-text', // ์ด๋ ๊ฒ ํ์
์ ์ง์ ํ ์๋ ์์ง๋ง ๋ฆฌํฐ๋ด ํ์
์ ์ง์ ์ง์ ํ ์ ์๋ค. |
| 5 | +) { |
2 | 6 | let result;
|
3 |
| - if (typeof n1 === 'number' && typeof n2 === 'number') { |
4 |
| - result = n1 + n2; |
| 7 | + if (typeof n1 === 'number' && typeof n2 === 'number' || resultConversion === 'as-number') { |
| 8 | + result = +n1 + +n2; //error ts(2365) -> n1, n2์ธ ๋ค๋ฅธ ์ธ์ ์ถ๊ฐ๋๋ฉด์ ์กฐ๊ฑด๋ฌธ์์์ ๋
ผ๋ฆฌ์ ํ๋ฆ์ด ์ถฉ๋ถํ ๋ช
ํํ์ง ์์ ๋ฐ์ํ ์ ์๋ค. ๋ฐ๋ผ์ ์ด ์ฝ๋์์ TypeScript๋ n1๊ณผ n2๊ฐ string ํ์
์ผ ๊ฐ๋ฅ์ฑ์ด ์๋ค๊ณ ํ๋จ, ์ธ์๋ค์ ์ฌ์ฉํ ๋ ๋ ๋ช
ํํ ํ์
์ ์๊ตฌ ๋ฐ๋ผ '+'๋ฅผ ์ถ๊ฐํจ, ์ด๋ ๋ฆฌํฐ๋ด ํ์
๊ณผ๋ ๋ฌด๊ดํ๋ค. |
5 | 9 | } else if (typeof n1 === 'string' && typeof n2 === 'string') {
|
6 | 10 | result = n1 + n2;
|
7 | 11 | } else {
|
8 | 12 | result = n1.toString() + n2.toString();
|
9 |
| - } // ํด๊ฒฐ ๋ฐฉ๋ฒ: if๋ฌธ์ผ๋ก typeof๋ก ๊ฐ ํ์
๋ค์ด ๋ฌด์์ธ์ง ์๋ณํ ํ ์ฐ์ฐ์ ์ ์ฉํ๋ค. ์ฐ์ฐ์ด ์ ์ฉ๋์ง ์๋ ํ์
๋ค์ ๋ชจ๋ string์ผ๋ก ํ๋ณํ ํ ์ฐ์ฐ์ ์์ผ์ฃผ๋ฉด ๋๋ค. ๋ฐ๋ผ์ ์ ๋์จ ํ์
์ผ๋ก ์ฌ๋ฌ ํ์
์ ์ ์ฐํ๊ฒ ์ฌ์ฉํ ์ ์์ง๋ง ์ด๊ฒ๋ค์ ํ์ฉํ ๋๋ ์ ํํ ์ด๋ค ํ์
์ ๋ฐ๋์ง์ ๊ดํ ๋ก์ง์ด ๋ณดํต ํจ์๋ ํด๋์ค ๊ตฌ์กฐ์ ๋ง์ด ํ์ํ๋ค. |
10 |
| - return result; |
| 13 | + } |
| 14 | + // if (resultConversion === 'as-number') { |
| 15 | + // return +result; |
| 16 | + // } else { |
| 17 | + // return result.toString(); |
| 18 | + // } |
11 | 19 | }
|
12 |
| -// Ts๊ฐ ์ผ๋ คํ๋ error์ ๊ทผ์์ ์๋์ ๊ฐ๋ค. |
13 |
| -// const b1: boolean = true; |
14 |
| -// const b2: boolean = false; |
15 |
| -// console.log(b1 + b2); |
| 20 | +// ๋ฆฌํฐ๋ด ํ์
์ด๋? ๋ฆฌํฐ๋ด ํ์
์ ํน์ ๋ณ์๋ ์ด๋ค ํ์
์ด์ด์ผ ํ๋์ง ์ ์ํ๋๊ฒ ์๋๋ค. ๋จ์ง ์ ํํ ์ด๋ค ๊ฐ์ธ์ง ์ ์ํ๋ ๊ฒ์ด๋ค. ์ด๋ฅผ ํ์ธํ๊ธฐ ์ํด์๋ ๋ง์ฐ์ค๋ฅผ ์ํ๋ ๊ฐ์ ํธ๋ฒํ๋ฉด ๋ฐํ๋๋ ๊ฐ์ด ๋ฌด์์ธ์ง ํ์ธ์ด ๋๋ค. Ts๋ ์์๊ฐ ์๋ก ์ ์ ํ์
๋ค์ ๊ตฌ์ฒด์ ์ผ๋ก ์ขํ๊ฐ๋ ๊ฒ์ผ๋ก ๋ณด์ธ๋ค. |
| 21 | +const combineAges = combine(20, 30, 'as-number'); |
| 22 | +console.log(combineAges); |
16 | 23 |
|
17 |
| -const CombineAges = combine(20, 30); |
18 |
| -console.log(CombineAges); |
| 24 | +const combinedStringAges = combine('20', '30', 'as-number'); |
| 25 | +console.log(combinedStringAges); |
19 | 26 |
|
20 |
| -const CombineNames = combine('Max', 'Anna'); |
21 |
| -console.log(CombineNames); |
| 27 | +const combineNames = combine('Max', 'Anna', 'as-text'); |
| 28 | +console.log(combineNames); |
0 commit comments