๊ธฐ์กด์ ์ ์๋์ด ์๋ ํ์ ์ ์๋ก์ด ํ์ ์ผ๋ก ๋ณํํด์ฃผ๋ ๋ฌธ๋ฒ
์์) ์ธํฐํ์ด์ค์ ์๋ ๋ชจ๋ ์์ฑ์ ์ํํ์ฌ ๋ค๋ฅธ ํ์ ์ผ๋ก ๋ณ๊ฒฝํ ์ ์์
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',
},
};