TypeScript: Classes Ep.2

Getters & Setters


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

  get name() {
    return this._name + " Lee";
  }

  set name(n: string) {
    this._name = n;
  }
}

const p1 = new Person("mark",39);
console.log(p1.name) // get을 하는 함수 getter
p1.name = "Jin"; // set을 하는 함수 setter
console.log(p1.name)

// mark Lee
// Jin Lee
  • 말 그대로 get 함수는 얻는 행위(세팅 한 걸 출력) set 함수는 세팅을 한다.
  • get에는 return이 포함되어야 한다.
  • getter 혹은 setter 하나를 삭제하면 컴파일 error가 발생한다.

readonly properties


class Person {
  public readonly name: string = "Mark";
  private readonly country: string;

  public constructor(private _name: string, public age: number) {
    this.country = "Korea";
  }

  hello() {
    this.country = "China";
		// readolny로 인해 값 변경 불가
  }
}

const p1 = new Person("Mark",39);
console.log(p1.name) 
p1.name = "Jin"; // readonly로 인해 값 변경 불가
console.log(p1.name)
  • readonly 키워드가 달려있으면 private던 public이던 초기화되는 영역에서만 값을 세팅할 수 있다. 다른 곳에서는 값을 변경할 수 없다.
  • 초기화하는 부분과 constructor 안에서만 readonly가 달려있는 private 프로퍼티의 값을 지정해 줄 수 있다. 그 외의 다른 메서드에서는 값을 변경할 수 없다.

Index Signatures in class


클래스 안에서 인덱스 시그니처 사용하기

index signature은 프로퍼티가 고정된 것이 아닌 동적으로 프로퍼티의 이름이 바뀔 때 사용하기 유용하다.

// 해당 형태로 만들기
// class => object
// {mark: "male", jade: "male"}
// {chloe: "female", alex: "male", anna: "female"}
class Students {
  [index: string]: string;
	// [index: string]: "male" | "female";
	// 위 코드가 조금 더 정확하다. 두 가지 값만 올 수 있도록 하기 때문이다.

  mark: "male" = "male"; // mark가 모든 반에 항상 존재할 때
}

const a = new Students;
a.mark = 'male';
a.jade = 'male';

console.log(a); 
// {mark: "male", jade: "male"}
  • 프로퍼티의 이름을 직접 쓰게되면 새로운 값을 넣게 되었을 때 또 직접 적어줘야 한다. 동적으로 처리가 불가능해진다.
  • 이런 경우, 프로퍼티가 동적으로 사용하게 하려면 index signature를 사용한다.
  • index signature은 초기값을 설정하지 않는다.
    값이 있을 수도 있고 없을 수도 있기 때문이다. 그래서 따로 최초값을 정하지 않는다.
  • mark라는 친구가 a,b에 항상 존재하고 male 값이 일때는 class 안에 mark: “male” = “male”; 형식으로 설정하면 된다. 나머지는 optional하게 등록이 가능하다.

Static Properties & Methods


프로퍼티와 메소드 앞에 static 키워드 사용하기

  • static method

      class Person3 {
        public static hello() {
          console.log("hello~?");
        }
      }
        
      const p3 = new Person3();
      // p3.hello();
        
      Person3.hello();
    
    • static을 붙이게 되면 object에서는 해당 함수를 메소드라고 생각하지 않는다.
      따라서 p3.hello(); 로는 사용할 수 없다.
      Person3.hellog(); 로 사용이 가능하다.
  • static property

      class Person3 {
        private static CITY = 'Seoul';
        public static hello() {
          console.log("hello~?", Person3.CITY);
        }
      }
        
      const p3 = new Person3();
      // p3.hello();
        
      Person3.hello();
      // Person3.CITY;
    
    • Person3을 new로 해서 object만들지 않더라도 CITY를 공유할 수 있다.
    • 클래스로 부터 만들어진 오브젝트에서 공통적으로 사용하고 싶은 데이터가 있다면 static을 넣어서 가져다 사용할 수 있도록 하면 좋다.
  • 서로 값을 공유하는 형태

      class Person3 {
        private static CITY = 'Seoul';
        public hello() {
          console.log("hello~?", Person3.CITY);
        }
        public change() {
          Person3.CITY = "Suwon";
        }
      }
        
      const p3 = new Person3();
      p3.hello();
        
      const p4 = new Person3();
      p4.hello();
        
      p3.change(); // 값 변경하기
        
      p4.hello(); // 변경된 값 다시 호출
    
    • p3에서 CITY의 데이터를 변경
    • p4에서 Person3.CITY를 꺼내면 p3에서 바뀐 데이터가 들어있다.

Comments