๊ธฐ๋ณธ ๊ฐ์ฒด ๋ฆฌํฐ๋ด๊ณผ 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; // ์ปดํ์ผ ์๋ฌ