[TIL] TypeScript์์ Record ํ์ ํ์ฉ
ํ์ ์ง์ ์ ์ด๋ ค์์ด ์์ด ์์นํ๋ ์ค Record๋ผ๋ ๊ฒ์ ๋ฐ๊ฒฌํด์ ์ ๋ฆฌํด๋ณด์๋ค
"Record" ํ์ ์ ๊ฐ์ฒด ํ์ ์ ์ ์ํ ๋ ์ฌ์ฉ๋๋ค๊ณ ํ๋ค.
- Record<Key, Value>
type RecordEx = Record<string, number>;
์์ ์์๋, RecordEx๋ ๋ฌธ์์ด ํค์ ์ซ์ ๊ฐ์ผ๋ก ์ด๋ฃจ์ด์ง ๊ฐ์ฒด๋ฅผ ๋งํ๋ค.
string์ ํค์ ํ์ ์ด๊ณ number๋ ๊ฐ์ ํ์ ์ธ ๊ฒ.
๋์ถฉ ์ฃผ๋ก ์ด๋ฐ ์์ผ๋ก ์ฌ์ฉ๋๋ ๊ฒ
// ์ฌ์ฉ์ ์ ๋ณด ๊ฐ์ฒด
type User = Record<"id" | "username" | "email", string>;
// ๋์๋ณ ์ธ๊ตฌ์
type PopulationByCity = Record<"Seoul" | "New York" | "Tokyo", number>;
์ฌ์ฉ์ ์ ๋ณด๊ฐ์ฒด์ ๋์๋ณ ์ธ๊ตฌ์์ ๋ํ ๋ฐ์ดํฐ๋
const users: User = {
user1: { id: "1", username: "Ahri", email:"pop_star@aa.com" },
user2: { id: "2", username: "Zoe", email:"bubble@aa.com" },
user3: { id: "3", username: "Izreal", email:"lux@aa.com" },
};
const cityPopulations: PopulationByCity = {
Seoul: 9720846,
New York: 8398748,
Tokyo: 13929286
};
์ด๋ฐ์์ผ๋ก ๋์ด์์ ๊ฒ์ธ๋ฐ ์ด๋ ๊ฒ ๊ฐ๋จํ๊ฒ ํํ์ด ๋๋ ๊ฒ์ด๋ค.
Record๋ฅผ ์ฌ์ฉํ์ง ์๊ณ ํ์ ์ ์ง์ ํ๊ฒ ๋์๋ค๋ฉด,
interface User {
id: string;
username: string;
email: string;
// or
[key: string]: string;
}
interface PopulationByCity {
[key: string]: number;
}
์ด๋ฐ์์ผ๋ก ์ ์์ ๊ฒ์ด๋ค.
๊ทผ๋ฐ ์ฌ์ค ํค-๋ฐธ๋ฅ๊ฐ ์ด๋ ๊ฒ ๋ ๊ฐ์ ๊ฒ๋ ์๋๊ณ ๋ง์ฝ์ id๊ฐ์ด number๋ผ๋ฉด ๊ตณ์ด Record๋ฅผ ์ฐ์ง ์์๋ ๋ ๊ฒ์ด๋ค
- ๋์ผํ ํ์ ์ ๊ฐ์ง ์ฌ๋ฌ ํ๋กํผํฐ๋ฅผ ๊ฐ์ง๋ ๊ฐ์ฒด๋ฅผ ์์ฑํ๊ฑฐ๋ ์ ์ํด์ผ ํ ๋
- ๊ฐ์ฒด์ ํค๋ฅผ ๋์ ์ผ๋ก ์์ฑํ๊ณ , ํด๋น ํค์ ๊ฐ์ ๋งคํํ ๋.
๋ ์ ์ฉํ๊ฒ ์ฐ์ธ๋ค. ํ์ง๋ง ๋ญ ์ฐ๋ ์์ !
๋์ ์ผ๋ก ํ๋กํผํฐ ์์ฑ
function createDynamicRecord(keys: string[]): Record<string, number> {
const dynamicRecord: Record<string, number> = {};
keys.forEach((key, index) => {
dynamicRecord[key] = index;
});
return dynamicRecord;
}
const dynamicData = createDynamicRecord(["one", "two", "three"]);
// dynamicData: { one: 0, two: 1, three: 2 }
ํค-๊ฐ ์์ ๊ณ์ ๋์ ์ผ๋ก ์ถ๊ฐํ ์ ์๋ค.
์ด๊ฒ๋ ๋ง์ฐฌ๊ฐ์ง๊ณ Record๋ฅผ ์ฌ์ฉํ์ง ์์๋ ๋์ง๋ง, ๋ถํ์ํ ๋ฐ๋ณต์ ์ค์ผ ์ ์๋ค.
ํค-๊ฐ ๋ณํ
type InvertedRecord<T extends Record<string, any>> = {
[K in keyof T]: K;
};
const fruitNames = {
apple: "red",
banana: "yellow",
orange: "orange",
};
type InvertedFruitNames = InvertedRecord<typeof fruitNames>;
// InvertedFruitNames: { apple: "apple"; banana: "banana"; orange: "orange"; }
๊ธฐ์กด ๊ฐ์ฒด์ ํค๋ฅผ ํด๋น ํค์ ๋์ผํ ๊ฐ์ผ๋ก ๋ณํํ๋ ์์์ด๋ค.
- InvertedRecord ํ์ ์ ์ ๋ค๋ฆญ T๋ฅผ ๋ฐ์์์ T์ ํค-๊ฐ ์์ ๋ณํ
- InvertedFruitNames๋ InvertedRecord๋ฅผ ์ฌ์ฉํ์ฌ fruitNames ๊ฐ์ฒด์ ํค-๊ฐ ์์ ๋ณํํ ๊ฒฐ๊ณผ๋ฅผ ์ ์ฅํ๋ ํ์
์ด์ ์กฐ๊ธ ๋ ์ต์ํ๊ฒ Record๋ฅผ ์ฌ์ฉํ ์ ์์ ๊ฑฐ ๊ฐ๋ค.