[TypeScript] ๋งต๋“œ ํƒ€์ž…(Mapped Type)

๐Ÿ“„ ๋งต๋“œ ํƒ€์ž…(Mapped Type)

๋งต๋“œ ํƒ€์ž…์€ ๊ธฐ์กด์— ์ •์˜๋˜์–ด ์žˆ๋Š” ํƒ€์ž…์„ ์ƒˆ๋กœ์šด ํƒ€์ž…์œผ๋กœ ๋ณ€ํ™˜ํ•ด ์ฃผ๋Š” ๋ฌธ๋ฒ•์ž…๋‹ˆ๋‹ค.

์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ map() API ํ•จ์ˆ˜๋ฅผ ํƒ€์ž…์— ์ ์šฉํ•œ ๊ฒƒ๊ณผ ๊ฐ™์€ ํšจ๊ณผ๋ฅผ ๊ฐ€์ง‘๋‹ˆ๋‹ค.

๐Ÿ“„ ๋งต๋“œ ํƒ€์ž… ๊ธฐ๋ณธ ๋ฌธ๋ฒ•

{ [ P in  K ] : T }
{ [ P in  K ] ? : T }
{ readonly [ P in  K ] : T }
{ readonly [ P in  K ] ? : T }

๐Ÿ“„ ๋งต๋“œ ํƒ€์ž… ์˜ˆ์ œ

  • Heroes ๋Š” Hulk, Capt, Thor๋ผ๋Š” ํ‚ค๋ฅผ ์œ ๋‹ˆ์˜จ ํƒ€์ž…์œผ๋กœ ๊ฐ€์ง„๋‹ค.
  • HeroAges์— Heroes์˜ ํ‚ค์˜ ํƒ€์ž…์„ number๋กœ ๋ฐ”๊พธ๋Š” ๋งต๋“œ ํƒ€์ž… ๋ฌธ๋ฒ•์„ ์ ์šฉํ–ˆ๋‹ค.
  • ์ƒ์ˆ˜ ages๋Š” ํ‚ค๊ฐ’์ด number์ธ HeroAges๋ฅผ ํƒ€์ž…์œผ๋กœ ๊ฐ€์ง„๋‹ค.
type Heroes = "Hulk" | "Capt" | "Thor";
type HeroAges = { [K in Heroes]: number };
const ages: HeroAges = {
  Hulk: 33,
  Capt: 100,
  Thor: 1000,
};

์ถœ์ฒ˜

Leave a comment