[TypeScript] 7장 클래스

 

1. 클래스 (Classes) 와 상속(Inheritance)

타입스크립트에서 클리스는 class 키워드로 정의되며, 상속은 extends 키워드를 사용해 구현합니다.

class Animal {
    constructor(public name: string) {}
}

class Dog extends Animal {
    bark() {
        console.log(`${this.name} says woof!`);
        
    }
}

const dog = new Dog("Eddy");
dog.bark(); // 출력: Eddy says woof!

2. 접근 지정자 

  • public: 모든 곳에서 접근 가능
  • private: 클래스 내부에서만 접근 가능
  • protected: 클래스와 그 자식 클래스에서 접근 가능.
class Spc {
    public publicProp: string;
    private privateProp: string;
    protected protectedProp: string;


    constructor() {
        this.publicProp = `public state`;
        this.privateProp = `private state`;
        this.protectedProp = `protected state`;
    }

    showPrivate() {
        console.log(this.privateProp);
    }
}

const example = new Spc();
console.log(example.publicProp); // public state
example.showPrivate(); // private state
// console.log(example.privateProp); // Error 'private' is private

3. ECMAScript 비공개 필드

ECMAScript에서 비공개 필드는 # 기호를 사용하여 정의합니다.

class ECMA {
    #privateField: string;

    constructor() {
        this.#privateField = "i am private";
    }

    getPrivateField() {
        return this.#privateField;
    }
}

const e = new ECMA();
console.log(e.getPrivateField()); // i am private 
console.log(e.#privateField); // Error: "privateField" is private;

4. 읽기 전용 지정자

readonly 키워드를 사용하여 읽기 전용 프로퍼티를 정의할 수 있습니다.

class ReadOnly {
    readonly name: string;

    constructor(name:string) {
        this.name = name;
    }
}

const readonly = new ReadOnly("James");

console.log(readonly.name); // "James"
// console.log(readonly.name = "Kyoo"); // Error: "Kyoo" is read only!

5. 매개변수 프로퍼티 

생성자의 매개변수에 접근 지정자를 붙이면 자동적으로 프로퍼티가 생성됩니다.

class Person {
    constructor(public name: string, private age: number) {}
}

const person = new Person("Jim", 45);
console.log(person.name); // Jim
// console.log(person.age); // Error: "age" is private

6.접근자

접근자는 프로퍼티의 getter와 setter를 정의하는 데 사용됩니다.

class Accessor {
    private _value: number;

    constructor(value: number) {
        this._value = value;
    }

    get value() {
        return this._value;
    }

    set value(newValue: number) {
        this._value = newValue;
    }
}

const accessor = new Accessor(10);
console.log(accessor.value); // 10
accessor.value = 20;
console.log(accessor.value); // 20

7. 전역 프로퍼티

전역 프로퍼티는 클래스의 인스턴스에 접근할 수 있는 프로퍼티로, 일반적으로 static 키워드를 사용합니다.

class StaticExample {
    static staticProperty: string = "i am static mode";
}

console.log(StaticExample.staticProperty);

8. 추상 클래스

추상 클래스는 abstract 키워드를 사용해 정의하며, 직접 인스턴스화할 수 없습니다. 자식 클래스에서 구현해야 하는 메서드를 정의할 수 있습니다.

abstract class Shape {
    abstract area(): number;
}

class Circle extends Shape {
    constructor(private radius: number) {
        super();
    }

    area() {
        return Math.PI * this.radius ** 2;
    }
}

9. 고급 기법

  • 생성자 함수: 생성자 내에서 필요한 초기화를 수행
  • 인터페이스로써 클래스 사용: 클래스가 특정 인터페이스를 구현하게 할 수 있음
interface Drawable {
    draw(): void;
}

class Rectangle implements Drawable {
    constructor(private width: number, private height: number) {}

    draw() {
        console.log(`Drawing a rectangle of width ${this.width} and height ${this.height}`);
        
    }
}

const rectangle = new Rectangle(10,5);
rectangle.draw();

 

 

GitHub - Koras02/typescript-bloging

Contribute to Koras02/typescript-bloging development by creating an account on GitHub.

github.com

 

 

LIST

'Front-End > TypeScript' 카테고리의 다른 글

[Typescript] 9장 제네릭  (0) 2025.02.24
[Typescript] 8장 열겨형  (0) 2025.02.23
[Typescript] 6장 유니언 타입과 교차 타입  (0) 2025.02.18
[TypeScript] 5강 리터럴 타입  (0) 2025.02.15
[TypeScript] 4강 함수  (0) 2025.02.13