๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
  • [์„ฑ๊ณตํ•˜๋Š” ๊ฐœ๋ฐœ์ž] - Developer
Node/TypeScript

4.ํ•จ์ˆ˜ ํƒ€์ž…(JS →TS)

by Sein-JH 2021. 4. 15.
728x90

JavaScript ๐Ÿ’ฉ

function jsAdd(num1, num2) {  
  return num1 + num2;  
}

TS ๋ณ€ํ™˜ ํ•˜๊ธฐ

TypeScript โœจ

function add(num1: number, num2: number): number {  
  return num1 + num2;  
}

number ํƒ€์ž… ์ˆซ์ž๋ฅผ ์ง€์ •ํ•ด ์ฃผ๊ณ  return numberํƒ€์ž…์œผ๋กœ ์ง€์ •ํ•ด ์คฌ๋‹ค


JavaScript ๐Ÿ’ฉ

function jsFetchNum(id) {  
// code ...  
// code ...  ๋งŽ์€ ์ฝ”๋“œ
// code ...  
return new Promise((resolve, reject) => {  
    resolve(100);  
  });  
}

TS ๋ณ€ํ™˜ ํ•˜๊ธฐ

TypeScript โœจ

function fetchNum(id: string): Promise<number> {  
// code ...  
// code ...   ๋งŽ์€ ์ฝ”๋“œ
// code ...  
return new Promise((resolve, reject) => {  
    resolve(100);  
  });  
}

id: string ํƒ€์ž…์„ ํ• ๋‹นํ•˜๊ณ  Promise number๋กœ ๋ฆฌํ„ดํ•ด ์คฌ๋‹ค


ํ•จ์ˆ˜ ํƒ€์ž… ์ด์šฉ

JavaScript โœจ => TypeScript

Optional parameter

์ด๋ฆ„์„ ๋งŒ๋“œ๋Š” ํ•จ์ˆ˜ ์ œ์ž‘

function printName(firstName: string, lastName?: string) {  
  console.log(firstName);  
  console.log(lastName); // undefined  
}  
printName('Steve', 'Jobs');  
printName('Sein');  
printName('Mina');

๋‘๊ฐ€์ง€์˜ ์ธ์ž๋ฅผ ์„ค์ • ํ–ˆ์„ ๋•Œ 1๊ฐœ๋งŒ ์ธ์ž๋ฅผ ๋ณด๋‚ด๊ณ  ์‹ถ์„ ๋•Œ ์‚ฌ์šฉํ•œ๋‹ค.
?: (์‚ฌ์šฉํ•œ๋‹ค) Optional parameter
์ „๋‹ฌ ํ• ์ˆ˜ ์žˆ๊ณ  ์ „๋‹ฌ ์•ˆ ํ• ์ˆ˜๋„ ์žˆ๋‹ค

Default parameter

function printMessage(message: string = 'default message') {  
  console.log(message);  
}  
printMessage();

string = 'default message'

๊ธฐ๋ณธ ๋ฉ”์‹œ์ง€๋ฅผ ์„ค์ •ํ•˜๊ณ  ์‹ถ์„ ๋•Œ ์‚ฌ์šฉํ•œ๋‹ค. ํƒ€์ž… ์„ค์ • ํ›„ ์ž…๋ ฅํ•ด์ค€๋‹ค

Rest parameter

function addNumbers(...numbers: number[]): number {  
  return numbers.reduce((a, b) => a + b);  
}  
console.log(addNumbers(1, 2));  
console.log(addNumbers(1, 2, 3, 4));  
console.log(addNumbers(1, 2, 3, 4, 5, 0));

...numbers: number[]

...  Rest parameter ์ด๋‹ค 
ํ•จ์ˆ˜ ์ธ์ž๋ฅผ ์ „๋‹ฌ ํ• ๋•Œ ์‚ฌ์šฉํ•œ๋‹ค.

๋ฐฐ์—ด ์ธ์ž๋ฅผ ํ•œ๋ฒˆ์— ๋ฐ›์•„ ์˜ฌ ๋•Œ ์‚ฌ์šฉํ•œ๋‹ค.

'Node > TypeScript' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

7.Union  (0) 2021.04.17
6.Aliases  (0) 2021.04.15
5.๋ฐฐ์—ด Array or Tuple  (0) 2021.04.15
3.๊ธฐ๋ณธ ํƒ€์ž…(2)  (0) 2021.04.14
2. ๊ธฐ๋ณธ ํƒ€์ž…(1)  (0) 2021.04.14

๋Œ“๊ธ€