TypeScript #2 Generics

TaejoonPark·2022년 3월 31일
0

Typescript

목록 보기
2/5

Generics

  • 제네릭스를 써서 들어오게 될 것을 유추할 수 있게 된다. 유추를 하고 그에 맞게 세팅이 되는 느낌이다. any할 때랑 직접 비교해보면 제네릭스의 강점을 볼 수 있다.
  • 무엇이 들어가게 될지 정해지지 않았을 때 제네릭스를 쓸 수 있다.
  • 제네릭스를 쓰면 해당 변수에 어떤 것이 들어가있는지 볼 수 있고 내부에 있는 변수에 자동완성이 가능해진다.
function merge<T1, T2>(a: T1, b: T2) {
  return {
    ...a,
    ...b
  }
}

const merged = merge({foo: 1}, {bar: 2}); // merged에 마우스를 올리면 내부에 무엇이 있는지 볼 수 있다.
merged.foo // merged. 까지 치면 자동완성으로 내부에 있는 변수를 볼 수 있다.

즉, 어떤값이 들어올지 모를 때 any를 쓰면 변수에 마우스 올렸을 때 any 타입이라고 그대로 알려주는데 제네릭스를 쓰면 들어오는 값의 타입에 따라 동적으로 어떤 타입인지 알려준다. 아래 예를 하나 더 보자.

function wrap<T>(a: T) {
 	return {
      a
    }
}
const wrapped = wrap(30);
wrapped.a

Generics를 interface, type에 적용하기

interface

interface Items<T> {
  list: T[];
}

const items: Items<string> { // 만약 Generics안에 number를 쓰게 되면 아래 문자열 배열은 빨간 줄이 뜬다.
 	list: ['a', 'b', 'c'] 
}

type

type Items<T> = {
	list: T[];
}

const items: Items<string> {
 	list: ['a', 'b', 'c'] 
}

개수가 여러 개여도 상관없다.

type Items<T, V> {
	list: T[];
	value: V
}

const items: Items<string, number> {
 	list: ['a', 'b', 'c'],
    value: 1,
}

Generics를 Class에 적용해보기

class Queue<T> {
  list: T[] = [];

  // constructor(public list: T[]) {
  //   this.list = list;
  // }

  enqueue(item: T) {
    this.list.push(item);
  }

  dequeue() {
    return this.list.shift();
  }
}

const queue = new Queue<string>();
queue.enqueue('a');
console.log(queue.dequeue()); // a
profile
공유하는 것을 좋아하는 프론트엔드 개발자

0개의 댓글

관련 채용 정보