타입스크립트정리32 - 제네릭 클래스

박상훈·2023년 6월 15일

인프런 한입크기로 잘라먹는 타입스크립트 - 이정환님의 강의를 보고
내용을 정리한 포스팅입니다

🥇 제네릭 클래스

class NumberList {
  constructor(private list: T[]) {

    push(data:T){
      this.ist.push(data);
    }

    pop() {
      return this.list.pop();
    }

    print(){
      console.log(This.list);
    }
  }

  const numberList = new NumberList([1,2,3 ])
  numberList.pop();
  numberList.push(4)
  numberList.print() // [1,2,4] 로 출력됩니다
}

🥈 기존 만든 class를 다른 타입으로 변경하고싶을때

  • List 클래스를 제네릭 클래스로 변경
  • 생성자에 넘버타입 배열을 넣어주면 넘버타입의 리스트가 만들어집니다
  • 제네릭 클래스는 제네릭인터페이스,제네릭타입변수와 다르게 클래스 생성자를 호출할때 인수값 의 기준으로 추론합니다.
  • 그렇기에 앞에 타입을 굳이 명시할 필요가 없어집니다

변수를 스트링으로 바꾸면 스트링 리스트로 변경됩니다

class List<T> {
  constructor(private list: T[]) {

    push(data:T){
      this.ist.push(data);
    }

    pop() {
      return this.list.pop();
    }

    print(){
      console.log(This.list);
    }
  }

  const numberList = new List([1,2,3 ])
  numberList.pop();
  numberList.push(4)
  numberList.print() // [1,2,4] 로 출력됩니다
}
profile
다들 좋은 하루 되세요

0개의 댓글