본문 바로가기
TYPESCRIPT

클래스 2

by 일태찡 2023. 3. 21.

 

게터

 

class AccountingDepartment extends Department {
    private lastReport: string;

    // 게터
    get mostRecentReport() {
        if (this.lastReport) {
            return this.lastReport;
        }
        throw new Error('No report found.');
        
    }

    constructor(id: string, private reports: string[]) {
        super(id, 'Accouting');
        this.lastReport = reports[0];
    }
    
    addReport(text: string) {
        this.reports.push(text);
        this.lastReport = text;
    }
}

const accounting = new AccountingDepartment('A1',[]);
accounting.addReport('Something went wrong...');
// 메소드가 아닌 속성처럼 접근 () 사용 x
console.log(accounting.mostRecentReport); // Something went wrong...

 

게터 메서드는 값을 가지고 올 때 함수나 메서드를 실행하는 속성으로 개발자가 더 복잡한 로직을 추가할 수 있게 해 줍니다.

게터 메서드는 꼭 무언가를 반환하도록 작성해야 합니다.

생성한 게터는 메서드로서 이를 실행하는 게 아닌 속성으로 접근해야 합니다.

 

 

세터

 

class AccountingDepartment extends Department {
    private lastReport: string;

    get mostRecentReport() {
        if (this.lastReport) {
            return this.lastReport;
        }
        throw new Error('No report found.');
        
    }
    // 세터
    set mostRecentReport(value: string) {
        if (!value) {
            throw new Error('Please pass in a valid value!');
        }
        this.addReport(value)
    }

    constructor(id: string, private reports: string[]) {
        super(id, 'Accouting');
        this.lastReport = reports[0];
    }
    
    addReport(text: string) {
        this.reports.push(text);
        this.lastReport = text;
    }
}

const accounting = new AccountingDepartment('A1',[]);
accounting.addReport('Something went wrong...');
// 세터 역시 속성에 접근하듯 설정
accounting.mostRecentReport = 'Hi Setter!'
console.log(accounting.mostRecentReport); // Hi Setter!

 

세터 메서드는 저장하고자 하는 어떤 로직이든 실행할 수 있습니다.

게터와 세터는 로직을 캡슐화하고 속성을 읽거나 설정하려 할 때 실행되어야 하는 추가적인 로직을 추가하는 데 유용합니다.

 

 

정적 속성과 메서드

 

class Department {
    // 정적 속성
    static Year = 2023;
    
    constructor(private readonly id: string, public name: string) {
        this.id;
        this.name;
        console.log(this.Year) // 에러
    }

    // 정적 메서드
    static createEmployee (name: string) {
        return {name: name};
    }
}

const employee1 = Department.createEmployee('Jung');
console.log(employee1, Department.Year); // {name: 'Jung'} 2023

 

정적 속성과 메서드를 사용하여 클래스의 인스턴스에서 접근할 수 없는 속성과 메서드를 클래스에 추가할 수 있습니다.

클래스를 기반으로 생성된 객체가 아니라 클래스에서 직접 호출하는 속성과 메서드를 의미합니다.

 

 

클래스 내에서 이 정적 속성이 없다는 에러가 나오는데 this는 클래스를 기반으로 생성된 인스턴스를 참조하기 때문입니다.

정적 속성과 정적 메서드는 인스턴스에서 유효하지 않으며 전체적인 개념은 인스턴스와 분리되어 있습니다.

따라서 this 키워드로 접근하는 것은 불가능하며 접근하기 위해선 클래스 이름인 Department를 사용하여 클래스 내부에서도 접근할 수 있습니다.

 

 

추상 클래스

 

특정 클래스를 사용하여 작업하거나 특정 클래스를 확장시키는 개발자들이 특정 메서드를 구현하거나 재정의하도록 해야 하는 경우가 있는데 이에 추상 클래스를 사용할 수 있습니다.

즉 추상 클래스는 인스턴스화될 수 없고 확장되어야 하는 클래스를 의미합니다.

기본 클래스를 기반으로 모든 클래스에서 특정 메서드를 사용할 수 있는지 확인하고 특정 버전에 따라 달라지게 하는 것입니다.

 

// 여기
abstract class Department {
    protected employees: string[] = [];
    
    constructor(protected readonly id: string, public name: string) {
        this.id;
        this.name;
        console.log(this.Year);
    }

    static createEmployee (name: string) {
        return {name: name};
    }

    // 여기
    abstract describe(this: Department): void;

    addEmployee(employee: string) {
        this.employees.push(employee)
    }

    printEmployeeInformation() {
        console.log(this.employees.length);
        console.log(this.employees)
    }
}

 

메서드의 형태와 메서드의 구조가 어떤 것인지를 정의하고 상속 클래스로 내리면 아래와 같이 상속 클래스에는 추상 메서드 describe가 입력되지 않았음을 알립니다.

 

 

class ITDepartment extends Department {
    constructor (id: string, public admins: string[]) {
        super(id, 'IT');
        this.admins = admins;
    }

    describe() {
        console.log('IT Department - ID: ' + this.id)
    }
}

 

이렇게 상속 클래스에 추상 메서드를 구체화하여 나타낼 수 있었습니다.

추상 클래스란 일부 상위 클래스를 기반으로 하는 모든 클래스가 일부 공통 메서드 또는 속성을 공유할 수 있게 합니다.

 

 

private 생성자

 

private 생성자를 이용한 싱글톤 클래스는 하나의 클래스에서 하나의 인스턴스, 하나의 객체만 만들겠다고 선언하는 것입니다.

 

class ITDepartment extends Department {
    // 여기
    private constructor (id: string, public admins: string[]) {
        super(id, 'IT');
        this.admins = admins;
    }

    describe() {
        console.log('IT Department - ID: ' + this.id)
    }
}

const newIT = new ITDepartment('B1', ['LEE']); // 에러

 

이렇게 생성자 함수 앞에 private를 적게 되면 다음과 같은 에러가 발생합니다.

 

 

이는 인스턴스 생성을 클래스 내부에서 진행하라는 말과 같으며 다음과 같이 해결할 수 있습니다.

 

class ITDepartment extends Department {

    private static instance: ITDepartment;

    private constructor (id: string, public admins: string[]) {
        super(id, 'IT');
        this.admins = admins;
    }
    
    static getInstance() {
        if(this.instance) {
            return this.instance;
        }
        this.instance = new ITDepartment('B1', ['LEE']);
        return this.instance;
    }

    describe() {
        console.log('IT Department - ID: ' + this.id)
    }
}

// 인스턴스 생성
const IT = ITDepartment.getInstance();

 

어제까지는 괜찮았는데 오늘 내용 처음 보면 너무 복잡하고 어렵네요... 복습 더 하고 다음엔 인터페이스입니다...

 

'TYPESCRIPT' 카테고리의 다른 글

고급 타입  (6) 2023.03.24
인터페이스  (7) 2023.03.23
클래스 1  (6) 2023.03.20
타입스크립트 컴파일러  (7) 2023.03.17
타입스크립트 기초 2  (6) 2023.03.13