본문 바로가기
카테고리 없음

Typescript 클래스(Class)

by Jinseok Kim 2021. 5. 6.
반응형

클래스(Class)

 

 

기본 class을 이용한 타입 정의

class Person {
    name: string;
    age: number = 0;
    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }

    sayHello() {
        console.log('안녕');
    }
}
  • 맴버 변수에서 name과 age을 타입정의하고 있으며 age는 초기값으로 0을 할당하고 있다.
  • constructor에서는 맴버 변수를 초기화하고 있다.

 

 

 

class 상속 개념

class Person {
    sayHello() {
        console.log('안녕');
    }
}

class Programmer extends Person {
  fixBug() {
      console.log('버그 수정')
  }
}

const programmer = new Programmer();
programmer.fixBug();
programmer.sayHello();

위와 같이 extends을 이용하여 Person의 class을 상속받으면 Programmer는 자기 자신의 메서드 뿐 아니라 Person의 메서드들 또한 사용할 수 있게 되었다.

 

 

 

활용 실습

class Person {
    name: string;
    constructor(name: string) {
        this.name = name;
    }
    sayHello() {
        console.log(`안녕 난 ${this.name}야`);
    }
}

class Programmer extends Person {
    constructor(name: string) {
        super(name);
    }
    sayHello() {
        super.sayHello();
        console.log(`직업은 개발자이고.`);
    }
}

const programmer = new Programmer('김진석');
programmer.sayHello();

//안녕 난 김진석야
//직업은 개발자이고.

 

 

 

 

클래스의 맴버 변수와 메서드의 접근 범위 설정

 

 

일반적인 접근 범위는 public, protected, private 로 나뉠 수 있다.

 

  • public: 외부에도 노출하면서 상속받는 쪽에서도 노출한다. (아무 범위를 적용하지 않을때의 기본값이다.)
  • protected: 외부에는 노출하지 않지만 상속받는 쪽에서는 노출한다.
  • private: 외부에도 노출하지 않고 상속받는 쪽에서도 노출하지 않는다.

 

 

- private 적용

class Person {
    private name: string; // private 적용
    constructor(name: string) {
        this.name = name;
    }
    sayHello() {
        console.log(`안녕 난 ${this.name}야`);
    }
}
//상속 쪽
class Programmer extends Person {
    constructor(name: string) {
        super(name);
    }
    sayHello() {
        super.sayHello();
        console.log(`직업은 개발자이고.`);
    }
}
//외부
const programmer = new Programmer('김진석');
programmer.sayHello();
console.log(programmer.name); //name 오류

name에 private을 적용하니 객체에서 사용하려하니 사용할 수 없다는 오류를 등장하게 한다.

 

 

 

 

-protected 적용

class Person {
    protected  name: string; //protected 적용
    protected constructor(name: string) { //protected 적용
        this.name = name;
    }
    sayHello() {
        console.log(`안녕 난 ${this.name}야`);
    }
}
//상속 쪽
class Programmer extends Person {
    constructor(name: string) {
        super(name);
    }
    sayHello() {
        super.sayHello();
        this.name //접근 가능
        console.log(`직업은 개발자이고.`);
    }
}
//외부
const programmer = new Programmer('김진석'); //new Programmer 생성 불가 오류
programmer.sayHello();
console.log(programmer.name); //name 오류 접근 불가
  • 마찬가지로 외부에는 노출하지 않는 특성을 가진 protected 또한 name을 외부에서 객체로서 사용하지 못하게 한다.
  • protected을 Person 클래스의 constructor에도 사용하면 외부에서 Person 클래스를 생성하지 못하게 하기도 한다.
  • 하지만 상속받는 쪽의 노출은 허용하기에 상속 받은 쪽에서 this.name과 같이 사용할 수 있다.

 

 

- private 대체인 ' # '

class Person {
    #name: string; // # 적용
    constructor(name: string) {
        this.#name = name;
    }
    sayHello() {
        console.log(`안녕 난 ${this.#name}야`);
    }
}
//상속 쪽
class Programmer extends Person {
    constructor(name: string) {
        super(name);
    }
    sayHello() {
        super.sayHello();
        this.#name //오류
        console.log(`직업은 개발자이고.`);
    }
}
//외부
const programmer = new Programmer('김진석');
programmer.sayHello();
console.log(programmer.#name); //오류
  • private로 마찬가지로 똑같은 기능이다. 다른 점은 자바스크립트의 새로운 문법이다. #을 지정하면 다른 똑같은 변수에도 #을 붙여줘한다.
  • 타입스크립트에서는 private,  # 둘다 사용할 수 있다.

 

 

 

 

readonly와 class의 조합 활용

class Person {
    readonly name: string;
    private readonly age: number;
    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }
}

const person = new Person('김진석', 26);
person.name = '김진석'; // name 오류. readonly로 인해 바꾸지 못함
  • readonly을 사용하면 값을 수정할 수 없는 변수 기능 또한 class에서 가능하다.
  • 하지만 contreuctor에서는 name과 age 값을 수정 할 수 있다.

 

 

 

편의성을 위한 타입스크립트 기능의 생략

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

const person = new Person('김진석', 26);
console.log(person.name, person.age);
  • 맴버 변수와 contructor의 매개 변수를 받아 초기화 시켜주는 코드를 작성하지 않아도 contructor의 매개변수 앞에 public과 같은 접근 범위 및 readonly와 같은 설정을 해주면 자동으로 맴버 변수가 되며 초기화 코드 또한 없어도 된다.
  • 이 모든게 타입스크립트에서만 가능하다.

 

 

static 키워드 그리고 정적 맴버 변수와 정적 메서드

class Person {
    static Adultage = 26;
    constructor(public name: string, public age: number) {}
    sayHello() {
        console.log(`안녕 난 ${this.name}야`);
        console.log(Person.getAdultage(this.age) ? '나는 성인이 아니야' : '나는 성인이야');
    }
    static getAdultage(age: number) {
        return Person.Adultage <= age;
    }
}

const person = new Person('김진석', 26);
person.sayHello();
console.log(`성인 판단 기준 나이: ${Person.Adultage}`);
  • static 키워드를 맴버 변수에 선언해주면 각 객체와 상관없이 고정 값이기 때문에 Person.Adultage와 같이 클래스 이름에 점을 이용하여 접근할 수 있게 되었다. 외부에서도 같은 방식으로 사용할 수 있다.
  • 하지만 age와 name은 static을 붙이지 않았기 때문에 정적이므로 this을 이용하여 객체를 통해 접근하고 있다는 것을 확인 할 수 있다.

 

 

추상 class

abstract class Person {
    constructor(public name: string) {}
    sayHello() {
        console.log(`안녕 난 ${this.name}야`);
    }
    abstract sayHello2(): void;
}

class Programmer extends Person {
    sayHello(){
        super.sayHello();
        console.log(`난 개발자야`);
    }
    sayHello2() {
        console.log(`반가워`);
    }
}

const person = new Person('김진석'); //오류: 추상 클래스는 객체를 생성할 수 없다.
const programmer = new Programmer('김진석2')
programmer.sayHello();
programmer.sayHello2();
  • abstract 키워드를 사용하면 class을 추상 class로 바꿀 수 있다.
  • 메서드에도 abstract 키워드를 사용할 수 있는 사용하게 되면 적용된 메서드는 상속 받은 쪽에 반듯이 정의해줘야한다.
반응형

댓글