Skip to Content
Sunbeen's Blog
Documents๊ตฌ TypescriptBasic_Grammer10. ๐ŸŸฆ TypeScript - readonly & ์ธ๋ฑ์Šค๋“œ ์‹œ๊ทธ๋‹ˆ์ฒ˜(Index Signature) ์ •๋ฆฌ

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