Frontend 개발자 - hyo.loui

νƒ€μž…μŠ€ν¬λ¦½νŠΈ - Union (μœ λ‹ˆμ˜¨) νƒ€μž… λ³Έλ¬Έ

Typescript

νƒ€μž…μŠ€ν¬λ¦½νŠΈ - Union (μœ λ‹ˆμ˜¨) νƒ€μž…

hyo.loui 2023. 1. 17. 20:58

🎯λͺ©μ  :

Type Script  Union μœ λ‹ˆμ˜¨|μœ λ‹ˆμ–Έ νƒ€μž…, 정리 및 볡슡


1. μœ λ‹ˆμ˜¨ νƒ€μž…μ΄λž€?

νƒ€μž…μ„ "or μ—°μ‚°μž"둜 2개 이상 넣을 수 있게 ν•΄μ€€λ‹€

// Union (A || B)

const printOut = (input: string | number) => {
  console.log(input);
};

printOut("hi"); // hi
printOut(22); // 22

 

πŸ§ͺλ‚˜μ˜ μ‹€ν—˜μ‹€

// Union (A || B)

const printOut = (input: string | number) => {
  return input;
};

const test_ = typeof printOut("hi"); // hi
console.log("πŸ‘‰πŸ‘‰  test_", test_); //πŸ‘‰πŸ‘‰  test_ string

const test__ = typeof printOut(22); // 22
console.log("πŸ‘‰πŸ‘‰  test__", test__); // πŸ‘‰πŸ‘‰  test__ number

typeof 둜 μ‹€μ œ νƒ€μž…μ΄ λ§žλŠ”μ§€ μ½˜μ†”μ— 좜λ ₯ ν•΄ λ³΄μ•˜λ‹€ ( 정상 )


2. μœ λ‹ˆμ˜¨ νƒ€μž…μ˜ μž₯점

ν•˜λ‚˜μ˜ νŒŒλΌλ―Έν„°κ°€

2가지 νƒ€μž…μ„ λ™μ‹œμ— μ†Œν™”ν•  수 있고, λ‹€λ₯Έ νƒ€μž…μ€ μ—λŸ¬λ‘œ κ±°λ₯Ό 수 μžˆλ‹€.

const getAge = (age: number | string) => {
  if (typeof age === "number") {
    age.toFixed();
    return age;
  }
  if (typeof age === "string") {
    return age;
  }
};
console.log(getAge(12), typeof getAge(12)); // 12 number
console.log(getAge("12"), typeof getAge("12")); // 12 string

 


3. νƒ€μž…λ³„λ‘œ λ‹€λ₯Έ λ™μž‘ κ΅¬ν˜„

νŒŒλΌλ―Έν„°μ— λ“€μ–΄μ˜€λŠ” νƒ€μž…μ„ if문으둜 μ„ λ³„ν•˜μ—¬,

각 λ‹€λ₯Έ λ™μž‘μ„ μ·¨ν•  수 μžˆλ‹€.

 

λ§Œμ•½ numberκ°€ λ“€μ–΄μ˜¨λ‹€λ©΄ paddind (space) κ°€ λŠ˜μ–΄λ‚˜λ„λ‘ ν•˜κ³ ,

string이 λ“€μ–΄μ˜¨λ‹€λ©΄ value μ•žμœΌλ‘œ string(λ¬Έμžμ—΄)이 λ“€μ–΄μ˜€κ²Œ ν•˜μ˜€λ‹€.

function padLeft(value: string, padding: string | number) {
  if (typeof padding === "number") {
    return Array(padding + 1).join(" ") + value;
  }
  if (typeof padding === "string") {
    return padding + value;
  }
  throw new Error(`Expected string or number, get ${padding}.`);
}

console.log(padLeft("Hello world", 4)); //    Hello world
console.log(padLeft("Hello world", "!!!")); // !!!Hello world
// console.log(padLeft("Hello world", true));// Error

 


 

 μ΅œμ’… 정리 

  1. μœ λ‹ˆμ˜¨μ€ νƒ€μž…μ„ 2가지 이상 μ‚¬μš©ν•  수 있게 λ§Œλ“€μ–΄ μ€€λ‹€
  2. νƒ€μž…κ³Ό νƒ€μž… 사이에, or μ—°μ‚°μž "|" λ₯Ό μ‚¬μš©ν•˜λ©΄ λœλ‹€.
  3. νƒ€μž…μ„ μ„ λ³„ν•˜μ—¬ 각기 λ‹€λ₯Έ λ™μž‘μ„ ν•˜λ„λ‘ λ§Œλ“€μ–΄ 쀄 수 μžˆλ‹€.