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

์˜ˆ์‹œ) ์ธํ„ฐํŽ˜์ด์Šค์— ์žˆ๋Š” ๋ชจ๋“  ์†์„ฑ์„ ์ˆœํšŒํ•˜์—ฌ ๋‹ค๋ฅธ ํƒ€์ž…์œผ๋กœ ๋ณ€๊ฒฝํ•  ์ˆ˜ ์žˆ์Œ

interface Obj {
   prop1: string;
   prop2: string;
}
type ChangeType<T> = { 
   [K in keyof T]: number;
};
type Result = ChangeType<Obj>;
/*
{ 
   prop1: number; 
   prop2: number; 
}
*/

Mapped Type ๋ฌธ๋ฒ•

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

์œ„ ๋ฌธ๋ฒ•์„ ์‚ฌ์šฉํ•˜์—ฌ ๊ฐ์ฒด ํƒ€์ž…์˜ ๋ชจ๋“  ์†์„ฑ์„ readonly๋‚˜ optional๋กœ ๋ณ€๊ฒฝํ•˜๋Š” ์ž‘์—…์„ ์‰ฝ๊ฒŒํ•  ์ˆ˜ ์žˆ๋‹ค

interface Person {
   name: string;
   age: number;
}
 
type ReadOnly<T> = {
   readonly [P in keyof T]: T[P];
};
 
type ParTial<T> = {
   [P in keyof T]?: T[P];
};
 
type PersonPartial = Partial<Person>;
type ReadonlyPerson = Readonly<Person>;
  • in : ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ์˜ for in ์ฒ˜๋Ÿผ ๋ฃจํ”„๋ฅผ ๋Œ๋ ค์ฃผ๋Š” ํ‚ค์›Œ๋“œ
  • keyof : ์ธํ„ฐํŽ˜์ด์Šค Obj ๊ฐ์ฒด ํƒ€์ž… ์†์„ฑ๋“ค์„ ๋ฝ‘์•„ ์œ ๋‹ˆ์˜จ์œผ๋กœ ๋งŒ๋“ค์–ด์ฃผ๋Š” ์—ญํ• ์„ ํ•จ

Mapped Type ํ™œ์šฉ

  • ๋‹จ์ˆœ ๊ฐ์ฒด ์ƒ์„ฑ ์˜ˆ์ œ
type T1 = { 
	[K in "prop1" | "prop2"]: boolean 
};
type Prop = 'prop1' | 'prop2';
 
type Make<T> = { 
	[K in Prop]: T 
};
 
type T1 = Make<boolean>;
  • ๊ฐ์ฒด ์†์„ฑ ๋ณ€๊ฒฝ
interface UserProfile {
   username: string;
   email: string;
   profilePhotoUrl: string;
}
 
type UserProfileUpdate = {
   [p in keyof UserProfile]?: UserProfile[p];
};
  • readonly, optional ์ œ๊ฑฐ
interface Person1 {
   name?: string;
   age?: number;
}
 
interface Person2 {
   readonly name: string;
   readonly age: number;
}
 
type Exclude_ReadOnly<T> = {
   // -readonly ๋ผ๋Š” ๋œป์€ readonly๋ฅผ ๋–ผ๋ผ ๋ผ๋Š” ์˜๋ฏธ์ด๋‹ค.
   // ๋ฐ˜๋Œ€๋กœ +readonly ๋Š” readonly๋ฅผ ์ถ”๊ฐ€ํ•˜๋ผ๋Š” ์˜๋ฏธ์ธ๋ฐ ์ •์ˆ˜๋ฅผ +1๋กœ ์•ˆ์“ฐ๋“ฏ์ด ๊ทธ๋ƒฅ ์ƒ๋žต ๊ฐ€๋Šฅํ•จ
   -readonly [P in keyof T]: T[P];
};
 
type Exclude_ParTial<T> = {
   // -? ๋ผ๋Š” ๋œป์€ ?๋ฅผ ๋–ผ๋ผ ๋ผ๋Š” ์˜๋ฏธ์ด๋‹ค.
   // ๋ฐ˜๋Œ€๋กœ +? ๋Š” ?๋ฅผ ์ถ”๊ฐ€ํ•˜๋ผ๋Š” ์˜๋ฏธ์ธ๋ฐ ์ •์ˆ˜๋ฅผ +1๋กœ ์•ˆ์“ฐ๋“ฏ์ด ๊ทธ๋ƒฅ ์ƒ๋žต ๊ฐ€๋Šฅํ•จ
   [P in keyof T]-?: T[P];
};
 
type PersonPartial = Exclude_ParTial<Person1>;
/*
type PersonPartial = {
    name: string;
    age: number;
}
*/
 
type ReadonlyPerson = Exclude_ReadOnly<Person2>;
/*
type ReadonlyPerson = {
    name: string;
    age: number;
}
*/
  • ์ค‘์ฒฉ ๊ฐ์ฒด ํƒ€์ž… ์ƒ์„ฑ
interface Person {
   name: string;
   age: number;
   language: string;
}
 
type Recorded<K extends string, T> = { [P in K]: T };
 
type T1 = Recorded<'p1' | 'p2', Person>;
 
const t: T1 = {
   p1: {
      name: 'ํ™๊ธธ๋™',
      age: 88,
      language: 'kor',
   },
   p2: {
      name: '๋ง์ปจ',
      age: 34,
      language: 'eng',
   },
};

์ฐธ๊ณ