- Record ์ ํธ๋ฆฌํฐ ํ์ ์ TypeScript์์ ์ ๊ณตํ๋ ๋ด์ฅ ํ์ ์ผ๋ก, ํน์ ํ์ ์ ํค์ ๊ฐ์ผ๋ก ๊ตฌ์ฑ๋ ๊ฐ์ฒด๋ฅผ ์ ์ํ ๋ ์ฌ์ฉ๋ฉ๋๋ค
- ํค(key): string ํ์ (์: "age", "score", "id" ๋ฑ).
- ๊ฐ(value): number ํ์ (์: 42, 100, 3.14 ๋ฑ).
- ์ฆ, ๋ชจ๋ ํค๊ฐ ๋ฌธ์์ด์ด๊ณ , ๋ชจ๋ ๊ฐ์ด ์ซ์์ธ ๊ฐ์ฒด๋ฅผ ๋ํ๋ ๋๋ค.
const scores: Record<string, number> = { math: 95, science: 88, history: 92 };'
์ ๊ฐ์ฒด๋ Record ํ์
์ ๋ถํฉํฉ๋๋ค. ํค๋ math, science, history (๋ชจ๋ string)์ด๊ณ , ๊ฐ์ 95, 88, 92 (๋ชจ๋ number)์
๋๋ค.
ํน์ง
- ๋์ ํค ํ์ฉ: ํค๊ฐ ๊ณ ์ ๋์ง ์๊ณ , ๋ฌธ์์ด์ธ ์ด๋ค ํค๋ ๊ฐ์ง ์ ์์ต๋๋ค.
- ๊ฐ ํ์ ๊ฐ์ : ๋ชจ๋ ๊ฐ์ number ํ์ ์ด์ด์ผ ํ๋ฉฐ, ๋ค๋ฅธ ํ์ (์: string, boolean)์ ๋ฃ์ผ๋ฉด ์ปดํ์ผ ์๋ฌ๊ฐ ๋ฐ์ํฉ๋๋ค.
const invalid: Record<string, number> = { name: "John" // ์๋ฌ: "John"์ number๊ฐ ์๋ };
- ๋น ๊ฐ์ฒด ๊ฐ๋ฅ: Record
ํ์ ์ ๊ฐ์ฒด๋ ์์ฑ์ด ์์ด๋ ์ ํจํฉ๋๋ค.
const empty: Record<string, number> = {};
๋ค๋ฅธ ํ์ ๊ณผ์ ๋น๊ต
- { [key: string]: number } ์ ๋์ผ: Record
๋ ์ธ๋ฑ์ค ์๊ทธ๋์ฒ { [key: string]: number }์ ๊ฐ์ ์๋ฏธ์ ๋๋ค. ํ์ง๋ง Record๋ ๋ ๊ฐ๊ฒฐํ๊ณ ๊ฐ๋ ์ฑ์ด ์ข์ต๋๋ค. - ์ ํ๋ ํค ํ์ : ํค๋ฅผ ํน์ ๋ฌธ์์ด ๋ฆฌํฐ๋ด๋ก ์ ํํ๋ ค๋ฉด Record<"key1" | "key2", number>์ฒ๋ผ ์ฌ์ฉํ ์ ์์ต๋๋ค.
const limited: Record<"width" | "height", number> = { width: 100, height: 200 // depth: 50 // ์๋ฌ: "depth"๋ ํ์ฉ๋์ง ์๋ ํค };
๊ฐ ํ์
์ผ๊ด์ฑ: ๋ชจ๋ ๊ฐ์ด number์ฌ์ผ ํ๋ฉฐ, undefined๋ null๋ ํ์ฉ๋์ง ์์ต๋๋ค (๋จ, Record์ฒ๋ผ ๋ช
์์ ์ผ๋ก ํ์ฉ ๊ฐ๋ฅ).