Skip to Content
Sunbeen's Blog
Documents๊ตฌ TypescriptBasic_Grammer11. ๐ŸŸฆ TypeScript ํด๋ž˜์Šค - ์ ‘๊ทผ ์ œ์–ด์ž, ์ธํ„ฐํŽ˜์ด์Šค, ์ถ”์ƒ ํด๋ž˜์Šค ์ •๋ฆฌ

11. ๐ŸŸฆ TypeScript ํด๋ž˜์Šค - ์ ‘๊ทผ ์ œ์–ด์ž, ์ธํ„ฐํŽ˜์ด์Šค, ์ถ”์ƒ ํด๋ž˜์Šค ์ •๋ฆฌ

๐Ÿ“Œ 1.ํด๋ž˜์Šค ๊ธฐ๋ฐ˜ ๊ตฌ์กฐ

class A1 { a: string; // ์ดˆ๊ธฐํ™” ๋˜์ง€ ์•Š์•˜๋‹ค๋Š” ์•Œ๋ฆผ ํ‘œ์‹œ (strict ๋ชจ๋“œ ์—๋Ÿฌ) b: string = "456"; // ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ดˆ๊ธฐํ™” } class A2 { a: string; b: string; // b: string = 123 ๊ธฐ๋ณธ๊ฐ’ default value constructor(a: string, b: string = 123) { this.a = a; this.b = b; } } class B { a: string = "123"; b: string = 123; method() { console.log(123); } } const a1 = new A("123"); const a2 = new A("123", 345); const a3: A = new A("123"); // ํด๋ž˜์Šค์˜ ์ด๋ฆ„์€ ๊ทธ ์ž์ฒด๋งŒ์œผ๋กœ๋„ ํƒ€์ž…์„ ๋‚˜ํƒ€ ๋‚ธ๋‹ค const b1: typeof AA = A; const b2: typeof A = new A("123"); // ์—๋Ÿฌ

๐Ÿ“Œ 2. ํด๋ž˜์Šค ์ ‘๊ทผ ์ œ์–ด์ž

  • class์— private, protected ์ถ”๊ฐ€๋จ
์ ‘๊ทผ ์ œ์–ด์žํด๋ž˜์Šค ๋‚ด๋ถ€์ƒ์†๋œ ํด๋ž˜์Šค(extends)ํด๋ž˜์Šค ์™ธ๋ถ€ ์ ‘๊ทผ(์ธ์Šคํ„ด์Šค)
publicโœ…โœ…โœ…
protectedโœ…โœ…โŒ
privateโœ…โŒโŒ
class A { public pub = "๊ณต๊ฐœ"; protected prot = "์ƒ์† ๊ฐ€๋Šฅ"; private priv = "๋น„๊ณต๊ฐœ"; // ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ์—์„œ private #b: number = 123; } class B extends A { show() { console.log(this.pub); // โœ… console.log(this.prot); // โœ… // console.log(this.priv) // โŒ private ์ ‘๊ทผ ๋ถˆ๊ฐ€ } } const b = new B(); console.log(b.pub); // โœ… console.log(b.prot); // โŒ console.log(b.priv); // โŒ

๐Ÿ“Œ 3. readonly

  • ์ฝ๊ธฐ ์ „์šฉ ์†์„ฑ. ์ดˆ๊ธฐํ™” ์ดํ›„ ๊ฐ’ ๋ณ€๊ฒฝ์ด ๋ถˆ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค.
interface A { readonly a: string; b: string; } const aaaa: A = { a: "hello", b: "world" }; aaaa.a = "123"; // โŒ Error: ์ฝ๊ธฐ ์ „์šฉ

๐Ÿ“Œ 4. interface์™€ class์˜ ๊ด€๊ณ„

  • interface๋Š” ์ถ”์ƒ์ ์ธ ํƒ€์ž… ์„ ์–ธ โ†’ ์ปดํŒŒ์ผ ๊ฒฐ๊ณผ๋กœ JS์—๋Š” ์กด์žฌํ•˜์ง€ ์•Š์Œ
  • class๋Š” ์‹คํ–‰ ๊ฐ€๋Šฅํ•œ ์ฝ”๋“œ๋กœ ๋ณ€ํ™˜๋จ โ†’ ๋Ÿฐํƒ€์ž„์—๋„ ์กด์žฌํ•จ
  • class์— private, protected ์ถ”๊ฐ€๋จ
  • ์ถ”์ƒ์— ์˜์กดํ•˜๊ณ , ๊ตฌํ˜„์— ์˜์กดํ•˜์ง€๋ง๋ผ (interface), (class)
// interface ์ถ”์ƒ // interface๋Š” ์‚ฌ๋ผ์ง interface A { readonly a: string; b: string; } // interface ๋ฉค๋ฒ„๋Š” public์œผ๋กœ ๊ตฌํ˜„ํ•ด์•ผ ํ•จ class B implements A { //private a: string = "hi" // โŒ Error: private์€ interface์™€ ํ˜ธํ™˜ ๋ถˆ๊ฐ€ //protected b: string = "world" // โŒ Error: protected๋„ ์•ˆ๋จ public a: string = "hi"; // โœ… OK public b: string = "world"; } class C extends B {} new C().a; new C().b;

๐Ÿ“Œ 5. ์ถ”์ƒ ํด๋ž˜์Šค (abstract)

๐Ÿงฉ ๊ฐœ๋…

abstract class๋Š” ์ง์ ‘ ์ธ์Šคํ„ด์Šคํ™”ํ•  ์ˆ˜ ์—†๋Š” ํด๋ž˜์Šค

abstract method๋Š” ๋ฐ˜๋“œ์‹œ ํ•˜์œ„ ํด๋ž˜์Šค์—์„œ ๊ตฌํ˜„ํ•ด์•ผ ํ•จ

abstract class D { private readonly a : string = '123'; b: string = '345'; c: string = 'wow'; abstract method(): void; // ์ถ”์ƒ ํด๋ž˜์Šค๋„ ์‹ค์งˆ ํ•จ์ˆ˜ ๋ฉ”์†Œ๋“œ๋ฅผ ๊ฐ€์งˆ ์ˆ˜์žˆ๋‹ค. method2() { return '3'; }
Last updated on