Notice
Recent Posts
Recent Comments
«   2026/02   »
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
Link
관리 메뉴

개발블로그

TypeScript - Generics 본문

TypeScript

TypeScript - Generics

춘식스 2022. 5. 27. 14:13

Generics

제네릭은 타입스크립트에서 함수, 클래스. interface, type을 사용하게 될 때 여러 종류의 타입에 대하여 호환을 맞춰야 하는 상황에서 사용하는 문법이다.

함수에서 Generics 사용하기

// 예시
function merge(a: any, b: any): any {
  return {
    ...a,
    ...b
  };
}

const merged = merge({foo: 1}, {bar: 1});

// 객체 A와 객체 B를 합쳐주는 merge라는 함수를 만든다고 가정
// A와 B가 어떤 타입이 올 지 모르기 때문에 이런 상황에서는 any 타입 사용 가능
// any = 모든 데이터 타입을 허용
// 이렇게 하면 타입추론이 모두 깨진것과 다름이 없다.
// 결과가 any 라는 것은 merged 안에 무엇이 있는지 알 수 없다는 것

// 제네릭 예시
function merge2<A, B>(a: A, b: B): A & B {
  return {
    ...a,
    ...b
  };
}

const merged2 = merge2({foo: 1}, {bar: 1});

// 제네릭을 사용 할 때는 <T>처럼 꺽쇠 안에 타입의 이름을 넣어서 사용
// 설정을 해주면 제네릭에 해당하는 타입에는 뭐든지 들어올 수 있게 된다.
// 사용 할 때 타입이 깨지지 않게 된다.
// 함수에 제네릭을 사용하게 된다면 함수의 파라미터로 넣은 실제 값의 타입을 활용하게 된다.

// 제네릭 예시2
function wrap<T>(param: T) {
  return {
    param
  };
}

const wrapped = wrap(10);

interface에서 Generics 사용하기

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

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

// Items<string>라는 타입을 사용하게 된다면,
// Items 타입을 지니고 있는 객체의 list배열은 string[] 타입을 지니고있게 된다.
// list가 숫자배열인 경우, 문자열인 경우, 객체배열, 또는 그 어떤 배열인 경우에도 하나의 interface만을 사용하여
// 타입을 설정 할 수 있다.

Type alias에서 Generics 사용하기

type에서 제네릭을 사용하는 방법은 interface에서 제네릭을 사용한 것과 매우 유사하다.
// 잘못된 예시
/*
interface Mobile8 {
  name: string;
  price: number;
  option: any;
}
*/

interface Mobile8<T> {
  name: string;
  price: number;
  option: T;
}

// const m1: Mobile8 = { // Error
// const m1: Mobile8<{color: string; coupon: boolean}> = { // 다른 방법
const m1: Mobile8<object> = {
  name: "s21",
  price: 1000,
  option: {
    color: "red",
    coupon: false
  }
};

// const m2: Mobile8 = { //Error
const m2: Mobile8<string> = {
  name: "s20",
  price: 900,
  option: "good"

class에서 Generics 사용하기

// 예시
// Queue 라는 클래스를 생성
// Queue 는 데이터를 등록 할 수 있는 자료형
// 먼저 등록(enqueue)한 항목을 먼저 뽑아올 수 (dequeue)있는 성질을 가지고있다.
// 실생활에서 접할 수 있는 간단한 대기줄

class Queue<T> {
  list: T[] = [];
  get length() {
    return this.list.length;
  }
  enqueue(item: T) {
    this.list.push(item);
  }
  dequeue() {
    return this.list.shift();
  }
}

const queue = new Queue<number>();
queue.enqueue(0);
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
queue.enqueue(4);
console.log(queue.dequeue());
console.log(queue.dequeue());
console.log(queue.dequeue());
console.log(queue.dequeue());
console.log(queue.dequeue());

컴파일 후 실행 결과

 

'TypeScript' 카테고리의 다른 글

TypeScript - Literal Types  (0) 2022.05.27
TypeScript - Class  (0) 2022.05.27
TypeScript - Type Alias  (0) 2022.05.27
TypeScript - Interface  (0) 2022.05.26
TypeScript 함수  (0) 2022.05.26
Comments