[TECH-QA] TypeScript์—์„œ ๊ฐ์ฒด ๋ฆฌํ„ฐ๋Ÿด์„ ๋ถˆ๋ณ€(immutable)์œผ๋กœ ์‚ฌ์šฉํ•˜๊ธฐ

๊ธฐ๋ณธ ๊ฐ์ฒด ๋ฆฌํ„ฐ๋Ÿด๊ณผ as const

const config = {
  apiUrl: "https://api.example.com",
  port: 8080,
  timeout: 5000
} as const;

// ํƒ€์ž…: { readonly apiUrl: "https://api.example.com"; readonly port: 8080; readonly timeout: 5000; }

// ๊ฐ’ ๋ณ€๊ฒฝ ์‹œ๋„ - ์—๋Ÿฌ ๋ฐœ์ƒ
// config.apiUrl = "https://new-url.com"; // ์˜ค๋ฅ˜: Cannot assign to 'apiUrl' because it is a read-only property.

// ์‚ฌ์šฉ ์˜ˆ์‹œ
function fetchData(url: string) {
  console.log(`Fetching from ${url}`);
}

fetchData(config.apiUrl); // ์ •์ƒ ์ž‘๋™

์ค‘์ฒฉ ๊ฐ์ฒด์™€ as const

const userSettings = {
  user: {
    name: "Alice",
    age: 30
  },
  preferences: {
    theme: "dark",
    notifications: true
  }
} as const;

// ํƒ€์ž…: { readonly user: { readonly name: "Alice"; readonly age: 30; }; readonly preferences: { readonly theme: "dark"; readonly notifications: true; }; }

// ๊ฐ’ ๋ณ€๊ฒฝ ์‹œ๋„ - ์—๋Ÿฌ ๋ฐœ์ƒ
// userSettings.user.name = "Bob"; // ์˜ค๋ฅ˜: Cannot assign to 'name' because it is a read-only property.

// ์‚ฌ์šฉ ์˜ˆ์‹œ
function displayUser(settings: typeof userSettings) {
  console.log(`User: ${settings.user.name}, Theme: ${settings.preferences.theme}`);
}

displayUser(userSettings);

๋ฐฐ์—ด๊ณผ as const

const colors = ["red", "green", "blue"] as const;

// ํƒ€์ž…: readonly ["red", "green", "blue"]

// ๋ฐฐ์—ด ์š”์†Œ ๋ณ€๊ฒฝ ์‹œ๋„ - ์—๋Ÿฌ ๋ฐœ์ƒ
// colors[0] = "yellow"; // ์˜ค๋ฅ˜: Cannot assign to '0' because it is a read-only property.

// ์‚ฌ์šฉ ์˜ˆ์‹œ
function pickColor(color: typeof colors[number]) {
  console.log(`Selected color: ${color}`);
}

pickColor(colors[0]); // ์ •์ƒ ์ž‘๋™: "red"
  • as const์˜ ํšจ๊ณผ: ๊ฐ์ฒด์™€ ๋ฐฐ์—ด์˜ ๋ชจ๋“  ํ”„๋กœํผํ‹ฐ๋ฅผ readonly๋กœ ๋งŒ๋“ค๊ณ , ๋ฆฌํ„ฐ๋Ÿด ํƒ€์ž…์œผ๋กœ ์ขํž™๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, string ๋Œ€์‹  "specific-value"๋กœ ํƒ€์ž…์ด ์ง€์ •๋ฉ๋‹ˆ๋‹ค.
  • ๋ถˆ๋ณ€์„ฑ ๋ณด์žฅ: ์ปดํŒŒ์ผ ํƒ€์ž„์— ๊ฐ’ ๋ณ€๊ฒฝ์„ ๋ฐฉ์ง€ํ•˜๋ฉฐ, ์ฝ”๋“œ์˜ ์•ˆ์ •์„ฑ์„ ๋†’์ž…๋‹ˆ๋‹ค.
  • ์‚ฌ์šฉ ์‚ฌ๋ก€: ์ƒ์ˆ˜ ๋ฐ์ดํ„ฐ, ์„ค์ • ๊ฐ์ฒด, ์—ด๊ฑฐํ˜•(enum) ๋Œ€์ฒด ๋“ฑ์— ์œ ์šฉํ•ฉ๋‹ˆ๋‹ค.
  • ์ œํ•œ์‚ฌํ•ญ: as const๋Š” ๊ฐ์ฒด๋ฅผ ์™„์ „ํžˆ ๋™๊ฒฐ(freeze)ํ•˜์ง€ ์•Š์œผ๋ฏ€๋กœ, ๋Ÿฐํƒ€์ž„์—์„œ Object.freeze์™€ ํ•จ๊ป˜ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

Object.freeze

const frozenConfig = Object.freeze({
  apiUrl: "https://api.example.com",
  port: 8080
}) as const;

// ๋Ÿฐํƒ€์ž„๊ณผ ์ปดํŒŒ์ผ ํƒ€์ž„ ๋ชจ๋‘ ๋ถˆ๋ณ€
// frozenConfig.apiUrl = "new-url"; // ์ปดํŒŒ์ผ ์—๋Ÿฌ
// frozenConfig.port = 3000; // ์ปดํŒŒ์ผ ์—๋Ÿฌ