TypeScript - 클래스1

Seung min, Yoo·2021년 5월 7일
0
post-thumbnail
interface User {
  name: string;
}
interface Product {
  id: string;
  price: number;
}

class Cart {
  user: User;
  store: Object;
  constructor(user: User) {
    this.user = user;
    this.store = {};
  }
  put (id: string, product: Product) {
    this.store[id] = product;
  }
  get(id: string) {
    return this.store[id];
  }
}
const cartJohn = new Cart({ name: 'john'});
const cartJay = new Cart({ name: 'jay'});

이전에는 함수를 통해서 새로운 타입을 만들었다면 클래스가 나온 후에는 클래스를 통해서 특정타입의 객체를 생성할 수 있게 되었다.


2. 타입스크립트에서는 속성과 메서드에 접근제한자를 갖을 수 있다.
es6에는 없는 것인데, 위의 코드를 예로 cart라는 클래스의 store라는 속성은 cart클래스 몸통에서만 접근할 수 있게 접근을 제한할 수 있다.

접근제한자에는 public, private, protected

interface User {
  name: string;
}
interface Product {
  id: string;
  price: number;
}

class Cart {
  user: User;
  private store: Object;
  constructor(user: User) {
    this.user = user;
    this.store = {};
  }
  put (id: string, product: Product) {
    this.store[id] = product;
  }
  get(id: string) {
    return this.store[id];
  }
}
const cartJohn = new Cart({ name: 'john'});
const cartJay = new Cart({ name: 'jay'});

위에서 store속성 앞에 private키워드를 붙여서 클래스 내부에서만 접근할 수 있게 만들 수 있으며, 밑에 cartJohn이라는 cart클래스로부터 만들어진 인스턴스는 store에 접근할 수 없는 것을 확인할 수 있다.

💡cartJohn.을 입력해보면 자동완성에 store속성이 없어진 것을 확인할 수 있다.

💡private와 protected로 키워드를 이용하면 인스턴스 레벨에서 접근을 할 수 없게 되는데, 이 둘의 차이는 cart라는 클래스를 상속할 수 있는데 상속을 한 하이타입에서도 private는 접근이 안되지만 protected는 접근이 가능하다.


타입스크립트에서 추가된 한 가지의 기능 중 하나는 생성자를 정의할 때 매개변수를 정의를 하는데, 매개변수에 속성을 정의하고 접근제한자를 같이 쓰게 되면 속성을 정의를 하고 동시에 전달받은 인자를 해당 속성에 할당하는 코드를 한번에 처리할 수 있게 된다.

class Cart {

  private store: object;
  
  constructor(protected user: User) {
    // this.user = user;
    this.store = {}
  }
  
  public put (id: string, product: Product) {
    this.user //이처럼 this.에서 user속성에 접근이 가능하게 된다.
    this.store[id] = product;
  }
  get(id: string) {
    return this.store[id];
  }
}
profile
이제 막 개발을 시작한 프로그래밍 입문자

0개의 댓글