TypeScript/ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ TypeScript

์ง„์ •ํ•œ ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ์˜ ์‹œ์ž‘, Union ํƒ€์ž…

Rainbow๐ŸŒˆCoder 2022. 4. 15. 16:36
728x90

์œ ๋‹ˆ์˜จ ํƒ€์ž…์€ ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ์—์„œ ์ฝ”๋”ฉํ•  ๋•Œ ๊ต‰์žฅํžˆ ๋งŽ์ด ์“ฐ๊ฒŒ ๋  ๊ฒƒ์ด๋‹ค.

OR ๋˜๋Š” ํ•ฉ์ง‘ํ•ฉ์œผ๋กœ ์ดํ•ดํ•˜๋ฉด ์ถฉ๋ถ„ํ•  ๊ฒƒ์ด๋‹ค.

type Direction = "left" | "right" | "up" | "down";
function move(direction: Direction) {
  console.log(direction);
}

ํ™˜์ƒ์ ์ธ ์ž๋™ ์™„์„ฑ!

type TileSize = 8 | 16 | 32;
const tileA: TileSize = 16;
//const tileB: TileSize = 10; //10 ํ˜•์‹์€ TileSize ํ˜•์‹์— ํ• ๋‹นํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.

 

<ํ™œ์šฉ ์˜ˆ์ œ>

//function : login -> success, fail

type SuccessState = {
  response: {
    body: string;
  };
};

type FailState = {
  reason: string;
};

function login(): SuccessState | FailState {
  return {
    response: {
      body: "logged in!",
    },
  };
}

ํ•œ๋‹จ๊ณ„ ๋” ๋ฆฌํŽ™ํ† ๋ง

type SuccessState = {
  response: {
    body: string;
  };
};

type FailState = {
  reason: string;
};

type LoginState = SuccessState | FailState;

function login(): LoginState {
  return {
    response: {
      body: "logged in!",
    },
  };
}

 

์‹ค๋ฌด ์Šคํƒ€์ผ๋กœ ๊ฐ€๋ฉด ์ด์ œ ํ”„๋ผ๋ฏธ์Šค ๋„์ž…!

function login(id: string, password: string): Promise<LoginState> {
/.../
  };
}

 

 

<์—ฐ์Šต> for...in๊ณผ ํ•จ๊ป˜ ์จ๋ณด๊ธฐ

type SuccessState = {
  response: {
    body: string;
  };
};

type FailState = {
  reason: string;
};

type LoginState = SuccessState | FailState;


function printLoginState(state: LoginState) {
  if ("response" in state) {
    console.log(`๐ŸŽ‰ ${state.response.body}`);
  } else {
    console.log(`๐Ÿ˜ญ ${state.reason}`);
  }
}
let ์ž…์žฅ: SuccessState = {
  response: {
    body: "์ž…์žฅ์™„๋ฃŒ!",
  },
};

printLoginState(์ž…์žฅ); //๐ŸŽ‰ ์ž…์žฅ์™„๋ฃŒ!

์œ„ ์˜ˆ์ œ๋Š” ์‚ฌ์‹ค ๊ดœ์ฐฎ์€ ์Šคํƒ€์ผ์€ ์•„๋‹ˆ๋ฏ€๋กœ

Discriminated Union ์„ ๋” ์ถ”์ฒœ

728x90