티스토리 뷰

TIL

[TIL] TypeScript Genric 소소한 꿀팁

hoon2hooni 2022. 9. 22. 17:58

TIL

Frontend Master 수업에서 Queue를 typescript로 구현된 코드에서 Generic이 활용되었습니다.

Generic에 대해 더 깊게 공부해 보았습니다.

1. 타입스크립트에서 만약 class를 통해 instance를 형성할 때 generic type을 정해주지 않으면 unknown으로 해석한다.

2. 타입스크립트에서 재귀적으로 type을 설정할 수 있다.

type QNode<T> = {
  value: T;
  next?: QNode<T>;
};

3. generic을 활용해서 아래와 같은 타입을 만들고 할당하게되면 generic안에 꼭 값을 넣어주어야 한다.

generic안에 꼭 값을 넣어주어야 한다.

함수나 class의 경우 는 아래와 같이 사용가능하다

함수의 넣는 인자로 인해 결과가 나온다

4. function과 class를 활용해서 generic을 사용하면 내부에서 genric값 사용 가능하다.

5. Generic 값의 타입을 extends로 타입의 범위를 한정해줄 수 있다.

전체 코드

//generic으로 재귀적인 타입 구현 가능
type QNode<T> = {
  value: T;
  next?: QNode<T>;
};

class Queue<T> {
  public length: number;
  private head: QNode<T> | undefined;
  private tail: QNode<T> | undefined;

  constructor() {
    this.head = this.tail = undefined;
    this.length = 0;
  }

  enqueue(item: T): void {
    const node = { value: item } as QNode<T>;
    this.length++;
    if (!this.tail) {
      this.tail = this.head = node;
    }
    this.tail.next = node;
    this.tail = node;
  }

  dequeue(): T | undefined {
    if (!this.head) {
      return undefined;
    }
    this.length--;
    const head = this.head;


    this.head = this.head.next;

    //free (garbage collector)
    head.next = undefined;

    return head.value;
  }

  peek(): T | undefined {
    return this.head?.value;
  }
}

const myQueue = new Queue();
myQueue.enqueue({ value: 3 });

References

The Last Algorithms Course You'll Need (ThePrimeagen)

https://frontendmasters.com/courses/algorithms/


Uploaded by N2T

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/08   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함