본문 바로가기
프로그래밍/typescsript

타입스크립트의 클래스

by 한코코 2022. 11. 23.

readonly

클래스 속성에 readonly 키워드를 사용하면 접근만 가능하다.

또한 constructor()함수에 초기값 설정 로직을 넣어줘야하므로 인자에 readonly 키워드를 추가해서 코드를 줄일 수 있다.

class Developer {
    readonly name: string;
    static wheels = 4; // 정적
    constructor(theName: string) {
        this.name = theName;
    }
    start(){
      console.log(Car.wheels); // static으로 선언한 속성은 this가 아니라 클래스명으로 부른다.
    }
}

// 줄여쓴 코드
class Developer {
  readonly name: string;
  constructor(readonly name: string) {
  }
}

 

 

 

 

Accessor (접속자)

타입스크립트는 객체의 특정 속성의 접근과 할당에 대해 제어할 수 있다.

이를 위해서는 해당 객체가 클래스로 생성한 객체여야한다.

get만 선언하고 set을 선언하지 않으면 자동으로 readonly로 인식된다.

class Developer {
  private name: string; // name 속성에 제약사항 부여
  // #을 붙이면 private와 같은 뜻이다 -> #name
  // #을 사용하려면 프라이빗 식별자는 ECMAScript 2015 이상을 대상으로 지정할 때만 사용할 수 있다.
  
  // Getter
  get name2(): string {
    return this.name;
  }

  // Setter
  set name2(newValue: string) {
    if (newValue && newValue.length > 5) {
      throw new Error('이름이 너무 깁니다');
    }
    this.name = newValue;
  }
}
const josh = new Developer();
josh.name = 'Josh Bolton'; // Error
josh.name = 'Josh';

 

getters / setters란?

private로 설정한 속성을 정의하면, 이 속성에 접근하기 위해서는 Getter, Setter 함수를 사용해야 속성을 정의할 수 있다.

Getter함수는 특정 값을 조회하려고 할때 사용하며, 반드시 return이 필요하다.

// Getter
get name(): string { return this.name; }

Setter함수는 파라미터로 무조건 어떤 값을 설정해 주어야한다.

// Setter
set name(newValue: string) {
  if (newValue && newValue.length > 5) {
    throw new Error('이름이 너무 깁니다');
  }
  this.name = newValue; // 값을 지정
}

Getter와 Setter 함수는 서로 같은 이름이라도 사용할 수 있다.

get name(){return...}
set name(value){this._name = value;}

 

 

 

 

Abstract Class (추상 클래스)

추상화는 프로퍼티나 메소드의 이름만 선언해주고 구체적인 기능은 상속 받는 쪽에서 구현해주는 것을 의미한다.

추상 클래스는 인터페이스와 비슷한 역할을 하면서 조금 다른 특징을 가지고 있다.

추상 클래서는 특정 클래스의 상속 대상이 되는 클래스이며 좀 더 상위 레벨에서 속성, 메서드의 모양을 정의한다.

// 추상 클래스
abstract class Car{
  color:string;
  constructor(color:string){
    this.color = color ;
  }
  start(){
    console.log('start')
  }
  abstract doSomething():void;
}

// 추상 클래스는 new 키워드로 인스턴스를 생성할 수 없다.
// 상속을 통해서만 사용가능
class Bargan extends Car{
  constructor(color: string){
    super(color);
  }
  doSomething(){
    alert(3);
  }
}

 

 

( 참고 블로그1, 공식사이트, 공식사이트Getter 참고유투브)

댓글