10. ๐ฆ TypeScript - readonly & ์ธ๋ฑ์ค๋ ์๊ทธ๋์ฒ(Index Signature) ์ ๋ฆฌ
๐ 1. readonly ํค์๋
readonly๋ ์ฝ๊ธฐ ์ ์ฉ ์์ฑ์ ์ ์ํ ๋ ์ฌ์ฉ๋ฉ๋๋ค.
interface A {
readonly a: string;
b: string;
}
const aaaa: A = { a: "hello", b: "world" };
aaaa.a = "123"; // Error
โ TypeScript๊ฐ ํ์ ์์ ์ฑ์ ์ง์ผ์ฃผ๋ ๊ธฐ๋ฅ ์ค ํ๋
๐ 2. ์ธ๋ฑ์ค๋ ์๊ทธ๋์ฒ (Index Signature)
- ๊ฐ์ฒด์ ์์ฑ์ด ์ด๋ค ํค์ ๊ฐ์ ํ์ ์ ๊ฐ์ง ์ ์๋์ง๋ฅผ ์ ์ ํ์ ์ผ๋ก ์ ์ธํ๋ ๋ฐฉ๋ฒ
- typescript์์ ์ฌ๋ฌ๊ฐ์ง ์์ฑ์ด ์กด์ฌ ํ ๋ ํ ์์ฑ์ ์ ๋ถ ์ฒ๋ฆฌํ ์ ์๋๋ก ์ฒ๋ฆฌ
- ๊ฐ์ฒด์ ์์ฑ์ด ์ด๋ค ํค์ ๊ฐ์ ํ์ ์ ๊ฐ์ง ์ ์๋์ง ์ ์ํ ๋
- JS๋ก ๋ณํ ์ ์กด์ฌํ์ง ์์ โ ํ์ ๊ฒ์ฌ์ฉ ๋ฌธ๋ฒ
type A = { [key: string]: string };
- ๋ชจ๋ ์์ฑ์ ํค๋ string, ๊ฐ์ string์ด์ด์ผ ํ๋ค๋ ๋ป
- ํค ์ด๋ฆ์ ์์ ๋กญ๊ฒ ์ง์ ๊ฐ๋ฅ (key, option, prop, ๋ฑ)
- JS๋ก ๋ณํ ์ ์กด์ฌํ์ง ์์ โ ํ์ ๊ฒ์ฌ์ฉ ๋ฌธ๋ฒ
// ํ์ฉ ์์
interface ConfigOptions {
[optionName: string]: string | number | boolean;
}
const appConfig: ConfigOptions = {
theme: "dark",
version: 1.2,
debug: true
// ์ต์
์ด ์ถ๊ฐ๋ ์ ์์
};
Last updated on