Typescript의 Class (2. 중급 기능)

eeensu·2023년 8월 5일
0

typescript

목록 보기
13/22
post-thumbnail

Getter와 Setter

ts 클래스에서는 프로퍼티에 접근하는 방식을 조절하기 위해 getter와 setter를 사용할 수 있다. 이를 통해 프로퍼티의 값을 가져오거나 설정하는 과정에서 추가적인 로직을 수행할 수 있다.

  • getter
    property를 불러오기만 하는 함수

  • setter
    property의 값을 수정하는 함수


constructor의 매개변수와 충돌을 방지하기 위해, get이 아닌 진짜 property는 언더바 _ 를 붙여 사용한다.
즉, get이 property 이고 진짜 property 값은 _property 인 것이다.

class Person {
    public constructor(private _name: string, private _age: number) {
        console.log(`${this.name}${this.age}가 생성되었습니다.`);
    }

    public get name(){
        return this._name;
    }
    
    public set name(name: string) {  
        console.log('name set 호출');
        this._name = name;
    }

    get age(){  
        return this._age;
    }
    
    set age(age: number) {
        console.log('age set 호출');
        this.age = age;
    }
}

const p1: Person = new Person('Park', 25);

console.log(p1.name);
p1.name = 'Dong';
console.log(p1.name);

/*
    Park과 25가 생성되었습니다.
    Park
    name set 호출
    Dong   
*/


Readonly

set은 할 수 없고 get만 할 수 있게 해주는 키워드이다. property를 바꾸지 못하게 하려고 할 때 사용하면 된다. public readonly 가 아닌 private readonly 인 경우에는 class 내부에서 set을 못하게 해준다.

class Person {
    public readonly gender: string = 'Male';
    private readonly country: string = 'Korea';

    constructor(private _name: string, private _age: number) {

    }
    
    public hello() {
        console.log(`hello! ${this.gender} `);
    }
}

const p1: Person = new Person('Mark', 35);
p1.gender = 'Female';				// 불가능


Index Signatures

property를 동적으로 할당할 수 있다. [index: string] 이란 뜻은 객체에 어떤 문자열(속성이름)이 와도 값을 할당하게 해주겠다는 뜻이다. property가 고정된 형태가 아니라 동적으로 이름이 들어오는 경우 고려해볼만한 좋은 기능이다.

type Gender = 'male' | 'female';

class Students {
   [index: string]: Gender;				// 동적으로 오는 속성에는 'male' 또는 'female' 문자열만 할당할 수 있다.

   mark: Gender = 'male';
}

const aClass = new Students();
aClass.timy = 'female';

const bClass = new Students();
bClass.alex = 'male';
bClass.chloe = 'male';

console.log(aClass);
console.log(bClass);

/*
   Students { mark: 'male', timy: 'female' }
   Students { mark: 'male', alex: 'male', chloe: 'male' }
*/


Static

클래스 레벨에서 정의된 정적 멤버(속성 또는 메서드)를 생성한다. 클래스 레벨의 동작이나 데이터와 관련된 것들을 다룰 때 유용하게 사용한다. static으로 선언된 정적 멤버는 인스턴스 끼리 그 값을 공유한다는 특징이 있다.
반면 생성자로 생성된 객체는 static 함수나 static property를 쓸 수 없다.

class Person {

    public static CITY: string = 'Busan';

    public  hello(): void{
        console.log('hello!', Person.CITY);
    }

    public change(city: string) {
        Person.CITY = city;
       
    }
}

const p1: Person = new Person();
p1.hello();

const p2: Person = new Person();
p2.hello();
p1.change('Seoul');
p2.hello();
	
/*
  hello! Busan
  hello! Busan
  hello! Seoul					// static으로 선언된 정적 멤버는 다른 생성자로 생성했더라도 값을 공유한다.
*/
profile
안녕하세요! 26살 프론트엔드 개발자입니다! (2024/03 ~)

0개의 댓글