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