๐Ÿ“˜ TypeScript/๋ฌธ์ œํ’€๊ธฐ (์ฝ”๋”ฉ์• ํ”Œ)

ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ ์ˆ™์ œ Part 1 (1~4) : ํ•จ์ˆ˜ ํƒ€์ž…์ง€์ •

Zoeeey 2023. 12. 10. 14:39

์ด๋ฆ„์„ ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ์ž…๋ ฅํ•˜๋ฉด ์ฝ˜์†” ์ถœ๋ ฅ

๊ทธ๋ฆฌ๊ณ  ํŒŒ๋ผ๋ฏธํ„ฐ๊ฐ€ ๋น„์–ด์žˆ์„ ์‹œ ๋น„์–ด์žˆ๋‹ค๊ณ  ์•Œ๋ ค์ฃผ๊ธฐ

let doConsole = function(name? :string): void {
  if(typeof name === 'string'){
    console.log(`์•ˆ๋…•ํ•˜์„ธ์š” ${name}`);
  } else { console.log(`์ด๋ฆ„์ด ์—†์Šต๋‹ˆ๋‹ค.`) }
}

doConsole('์ฒ ์ˆ˜')

ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ์ˆซ์ž ํ˜น์€ ๋ฌธ์ž๋ฅผ ๋„ฃ์œผ๋ฉด ์ž๋ฆฟ์ˆ˜ ์•Œ๋ ค์ฃผ๊ธฐ

let doConsole = function(numish? :string | number): number {
  if(typeof numish === 'string'){
    return numish.length;
  } else if(typeof numish === 'number') {
    return numish.toString().length;
  } else { return 0;}

}

console.log(doConsole('22233'))
console.log(doConsole(2233))

ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ์ž…๋ ฅ์‹œ ๊ฒฐํ˜ผ๊ฐ€๋Šฅ์—ฌ๋ถ€ ์•Œ๋ ค์ฃผ๊ธฐ

  1. ํŒŒ๋ผ๋ฏธํ„ฐ๋Š” ์›”์†Œ๋“(๋งŒ์›๋‹จ์œ„), ์ง‘๋ณด์œ ์—ฌ๋ถ€(true/false), ๋งค๋ ฅ์ ์ˆ˜ ('์ƒ' or '์ค‘' or 'ํ•˜')
  2. ์›”์†Œ๋“์€ ๋งŒ์› ๋‹น 1์ , ์ง‘๋ณด์œ ์‹œ 500์  & ๋ฏธ๋ณด์œ ์‹œ 0์ , ๋งค๋ ฅ์ ์ˆ˜๋Š” '์ƒ'์ผ ๋•Œ๋งŒ 100์ ์œผ๋กœ ๊ณ„์‚ฐ
  3. ์ด ์ ์ˆ˜๊ฐ€ 600์  ์ด์ƒ์ผ ๊ฒฝ์šฐ "๊ฒฐํ˜ผ๊ฐ€๋Šฅ"์„ return. ๊ทธ ์™ธ์—” ์•„๋ฌด๊ฒƒ๋„ returnํ•˜์ง€ ์•Š์Œ
type salary = number;
type hadHouse = boolean;
type charm = string;


let canMarrige = function(salary, house, charm) :string | void {
  let point :number = 0;
  point += salary;
  if(house){ point += 500 }
  if(charm === '์ƒ'){ point += 100 }
  if(point >= 600){ return '๊ฒฐํ˜ผ๊ฐ€๋Šฅ' }
}

console.log(canMarrige(700, false, '์ค‘'))
console.log(canMarrige(100, false, '์ƒ'))

๊ฐ€์œ„๋ฐ”์œ„๋ณด ํ•จ์ˆ˜ ๋งŒ๋“ค๊ธฐ

  1. '๊ฐ€์œ„', '๋ฐ”์œ„', '๋ณด' ๋ฌธ์ž๋“ค๋งŒ ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ์ž…๋ ฅํ•  ์ˆ˜ ์žˆ๊ณ 
  2. '๊ฐ€์œ„', '๋ฐ”์œ„', '๋ณด' ๋ผ๋Š” ๋ฌธ์ž๋“ค๋งŒ ๋‹ด์„ ์ˆ˜ ์žˆ๋Š” array ์ž๋ฃŒ๋งŒ return ํ•  ์ˆ˜ ์žˆ์Œ
  3. ์˜ˆ๋ฅผ ๋“ค๋ฉด ['๊ฐ€์œ„', '๋ณด', '๊ฐ€์œ„'] ์ด๋Ÿฐ๊ฑฐ return ๊ฐ€๋Šฅ
  4. ['๊ฐ€์œ„', '๋ฐ”๋ณด'] ์ด๋Ÿฐ๊ฑฐ returnํ•˜๋ฉด ์—๋Ÿฌ๋‚˜์•ผํ•จ 
type Rockpaperscissors = '๊ฐ€์œ„' | '๋ฐ”์œ„' | '๋ณด';

function play(choices: Rockpaperscissors[]): Rockpaperscissors[] {
  const validChoices: Rockpaperscissors[] = ['๊ฐ€์œ„', '๋ฐ”์œ„', '๋ณด'];

  // ๋ชจ๋“  ์„ ํƒ์ด ์œ ํšจํ•œ์ง€ ํ™•์ธ
  if (choices.every(choice => validChoices.includes(choice))) {
    return choices;
  } else {
    throw new Error('์œ ํšจํ•˜์ง€ ์•Š์€ ์„ ํƒ์ด ํฌํ•จ๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค.');
  }
}

// ํ…Œ์ŠคํŠธ
try {
  console.log(play(['๊ฐ€์œ„', '๋ณด'])); // ํ†ต๊ณผ
  // ์•„๋ž˜๋Š” ์œ ํšจํ•˜์ง€ ์•Š์€ '๋ฐ”๋ณด'๊ฐ€ ํฌํ•จ๋˜์–ด ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ์—๋Ÿฌ
  // console.log(play(['๊ฐ€์œ„', '๋ฐ”๋ณด'])); 
} catch (error) {
  console.error(error.message);
}

์ถœ์ฒ˜ : ์ฝ”๋”ฉ์• ํ”Œ https://codingapple.com/