느려도 한걸음씩

📘 TypeScript - 클래스 본문

FE develop/Typescript

📘 TypeScript - 클래스

hoj0806 2025. 5. 23. 17:21

 

 

 

 

JavaScript에서 클래스(class)는 객체를 생성하기 위한 일종의 템플릿입니다. TypeScript는 여기에 정적 타입접근 제어자(Access Modifiers) 등을 추가하여 객체지향 프로그래밍을 더욱 강력하게 지원합니다. 이번 글에서는 TypeScript에서의 클래스 문법과 주요 개념을 정리해보겠습니다.

 

 

 

🔧 기본 클래스 구조와 생성자

class Car {
    color: string;
    constructor(color: string) {
        this.color = color;
    }

    start() {
        console.log('go...');
    }
}

const bmw = new Car('red');
bmw.start();

TypeScript에서는 클래스 내의 프로퍼티를 선언만 해도 타입을 추론할 수 있지만, 명시적으로 선언해주는 것이 좋습니다.

 

🪪 멤버 변수 선언 생략하기: public, readonly

class Car {
    constructor(public color: string) {}
    start() {
        console.log('go...');
    }
}

public이나 readonly를 생성자 매개변수에 붙이면 별도로 멤버 변수를 선언하지 않아도 자동으로 바인딩됩니다.

 

 

🔒 접근 제한자(Access Modifiers)

1. public: 어디서든 접근 가능

class Car {
    public name: string = 'car';
    color: string;

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

    start() {
        console.log('go...');
    }
}

class Bmw extends Car {
    constructor(color: string) {
        super(color);
    }

    showName() {
        console.log(this.name); // 가능
    }
}

 

2. private: 클래스 내부에서만 접근 가능

class Car {
    private name: string = 'car';
    color: string;

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

    start() {
        console.log('go...');
        console.log(this.name);
    }
}

class Bmw extends Car {
    constructor(color: string) {
        super(color);
    }

    showName() {
        // console.log(this.name); ❌ 에러 발생
    }
}

 

3. protected: 자식 클래스에서 접근가능, 외부접근 불가능

class Car {
    protected name: string = 'car';
    color: string;

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

    start() {
        console.log('go...');
        console.log(this.name);
    }
}

class Bmw extends Car {
    constructor(color: string) {
        super(color);
    }

    showName() {
        console.log(this.name); // 가능
    }
}

const z4 = new Bmw('black')

console.log(z4.name) // 클래스 인스턴스에서 접근불가

 

🧊 readonly (읽기 전용)

class Car {
    readonly name: string;
    color: string;

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

    start() {
        console.log('go...');
        console.log(this.name);
    }
}

const z4 = new Car('black', 'Z4');
// z4.name = 'X5'; ❌ Error: 읽기 전용

readonly로 선언한 프로퍼티는 생성자 내부에서만 초기화 가능하며 이후 값 변경은 불가능합니다.

 

⚙️ static 프로퍼티

class Car {
    static wheels = 4;
    readonly name: string;
    color: string;

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

    start() {
        console.log('go...');
        console.log(this.name);
        console.log(Car.wheels);
    }
}

console.log(Car.wheels); // 클래스명으로 접근

static은 인스턴스가 아닌 클래스 자체에 속하는 값입니다.

 

🔮 추상 클래스(abstract)

abstract class Car {
    public name: string = 'car';
    color: string;

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

    start() {
        console.log('go...');
    }

    abstract doSomething(): void; // 상속받은 클래스에서 구현 필요
}

class Bmw extends Car {
    constructor(color: string) {
        super(color);
    }

    doSomething() {
        alert(3);
    }

    showName() {
        console.log(this.name); // ✔️ this로 접근
    }
}

추상 클래스는 인스턴스화할 수 없으며, 자식 클래스에서 abstract 메서드를 반드시 구현해야 합니다.

'FE develop > Typescript' 카테고리의 다른 글

📘 TypeScript - 유틸리티 타입  (0) 2025.05.26
📘 TypeScript - 제네릭  (0) 2025.05.26
📘 TypeScript - 리터럴, 유니온/교차 타입  (0) 2025.05.23
📘 TypeScript - 함수  (1) 2025.05.23
📘 TypeScript - 인터페이스  (0) 2025.05.23