[Daily morning study] TypeScript์ Utility Types (Partial, Pick, Omit ๋ฑ)
#daily morning study
TypeScript์ Utility Types
TypeScript๋ ๊ฐ๋ฐ์๊ฐ ๋์ฑ ํจ์จ์ ์ผ๋ก ์ฝ๋ ์์ฑํ ์ ์๊ฒ ๋๋ ์ฌ๋ฌ ๋ค์ํ ์ ํธ๋ฆฌํฐ ํ์
์ ์ ๊ณตํฉ๋๋ค. ์ด ๊ฐ์ด๋์์๋ Partial, Pick, Omit, Record, Exclude, Extract์ ๊ฐ์ ์ฃผ์ ์ ํธ๋ฆฌํฐ ํ์
์ ๋ํด ์ค๋ช
ํ๊ฒ ์ต๋๋ค.
1. Partial
Partial<T> ํ์
์ ์ฃผ์ด์ง ํ์
T์ ๋ชจ๋ ํ๋กํผํฐ๋ฅผ ์ ํ์ (optional)์ผ๋ก ๋ง๋ค์ด ์ค๋๋ค. ์ด ์ ํธ๋ฆฌํฐ๋ ํน์ ๊ฐ์ฒด์ ์ผ๋ถ ํ๋กํผํฐ๋ง์ ์
๋ฐ์ดํธํ ๋ ์ ์ฉํฉ๋๋ค.
์์
interface User {
id: number;
name: string;
email: string;
}
const updateUser = (id: number, userUpdates: Partial<User>) => {
// ์
๋ฐ์ดํธ ๋ก์ง
};
updateUser(1, { name: "์ ์ด๋ฆ" });
์ ์ฝ๋์์ userUpdates๋ User ์ธํฐํ์ด์ค์ ์ ํ์ ์ธ ํ๋กํผํฐ๋ค๋ง ํฌํจํ ์ ์์ต๋๋ค.
2. Pick<T, K>
Pick<T, K> ํ์
์ ์ฃผ์ด์ง ํ์
T์์ ํน์ ํ๋กํผํฐ K๋ง ์ ํํ์ฌ ์๋ก์ด ํ์
์ ์์ฑํฉ๋๋ค. ์ฃผ๋ก ํฐ ๊ฐ์ฒด์์ ์ผ๋ถ ํ๋กํผํฐ๋ง ํ์ํ ๊ฒฝ์ฐ์ ์ ์ฉํฉ๋๋ค.
์์
interface User {
id: number;
name: string;
email: string;
}
type UserPreview = Pick<User, "id" | "name">;
const user1: UserPreview = {
id: 1,
name: "์ฌ์ฉ์1",
};
์ ์์์์๋ UserPreview ํ์
์ด User ํ์
์์ id์ name ํ๋กํผํฐ๋ง ์ ํํ ํํ์
๋๋ค.
3. Omit<T, K>
Omit<T, K> ํ์
์ Pick๊ณผ๋ ๋ฐ๋๋ก, ํน์ ํ๋กํผํฐ K๋ฅผ ์ ์ธํ ์๋ก์ด ํ์
์ ๋ง๋ญ๋๋ค.
์์
interface User {
id: number;
name: string;
email: string;
}
type UserWithoutEmail = Omit<User, "email">;
const user2: UserWithoutEmail = {
id: 2,
name: "์ฌ์ฉ์2",
};
์ ์์์์๋ UserWithoutEmail ํ์
์ด User ํ์
์์ email ํ๋กํผํฐ๋ฅผ ์ ์ธํ ํํ์
๋๋ค.
4. Record<K, T>
Record<K, T> ํ์
์ ์ฃผ์ด์ง ํค K์ ๊ฐ T๋ฅผ ๊ฐ์ง ๊ฐ์ฒด ํ์
์ ์์ฑํฉ๋๋ค. ์ฃผ๋ก ์ฌ๋ฌ ๊ฐ์ ๊ฐ์ด ๋์ผํ ํ์
์ผ ๋ ์ ์ฉํฉ๋๋ค.
์์
type UserRoles = "admin" | "editor" | "viewer";
type RolePermissions = Record<UserRoles, string[]>;
const permissions: RolePermissions = {
admin: ["read", "write", "delete"],
editor: ["read", "write"],
viewer: ["read"],
};
์ ์ฝ๋์์๋ UserRoles ํ์
์ ๊ฐ ์ญํ ์ ๋ํด ๊ถํ์ ์ ์ํ๋ ๊ฐ์ฒด๋ฅผ ์์ฑํ์์ต๋๋ค.
5. Exclude<T, U>
Exclude<T, U>๋ ์ฃผ์ด์ง ํ์
T์์ U์ ํด๋นํ๋ ํ์
์ ์ ์ธํ ์๋ก์ด ํ์
์ ์์ฑํฉ๋๋ค.
์์
type AllNumbers = number | string | boolean;
type OnlyNumbers = Exclude<AllNumbers, string | boolean>; // number๋ง ๋จ์ต๋๋ค.
์ ์ฝ๋์์ OnlyNumbers๋ number ํ์
๋ง ํฌํจํฉ๋๋ค.
6. Extract<T, U>
Extract<T, U>๋ ์ฃผ์ด์ง ํ์
T ์ค์์ U์ ์๋ธํ์
์ ์ถ์ถํ์ฌ ์๋ก์ด ํ์
์ ์์ฑํฉ๋๋ค.
์์
type AllNumbers = number | string | boolean;
type StringOrNumber = Extract<AllNumbers, string | number>; // string | number
์ ์ฝ๋์์ StringOrNumber๋ string๊ณผ number ํ์
๋ง ํฌํจํฉ๋๋ค.
๋ง๋ฌด๋ฆฌ
TypeScript์ ์ ํธ๋ฆฌํฐ ํ์ ๋ค์ ํ์ ๊ด๋ฆฌ๋ฅผ ํจ์ฌ ์์ํ๊ฒ ๋ง๋ค์ด ์ฃผ๋ฉฐ, ์ฝ๋์ ๊ฐ๋ ์ฑ์ ๋์ด๋ ๋ฐ ๊ธฐ์ฌํฉ๋๋ค. ์ด๋ฐ ์ ํธ๋ฆฌํฐ ํ์ ๋ค์ ์ ํ์ฉํ๋ฉด ๋์ฑ ํจ์จ์ ์ด๊ณ ์์ ํ ์ฝ๋๋ฅผ ์์ฑํ ์ ์์ต๋๋ค. ๊ฐ ์ ํธ๋ฆฌํฐ ํ์ ์ ์ฌ์ฉ ์ฌ๋ก์ ํจ๊ป ์ฝ๋๋ฅผ ์์ฑํด๋ณด๋ฉฐ ์ตํ๋ณด์ธ์!