타입을 변수로 주고 싶을 때 사용한다.

function helloString(message: string): string {
  return message;
}

function helloNumber(message: number): number {
  return message;
}
function hello<T>(message: T): T {
  return message;
}

hello<string>('hi');

클래스 활용

class Person<T> {
  private name: T;

  constructor(name: T) {
    this.name = name;
  }
}

const someone = new Person<string>('max');
console.log(someone);

Generic with extends

class Person<T extends string | number> {
  private name: T;

  constructor(name: T) {
    this.name = name;
  }
}

const someone = new Person(true); // error
console.log(someone);

Generic with multiple type

class Person<T, K> {
  private name: T;
  private age: K;

  constructor(name: T, age: K) {
    this.name = name;
    this.age = age
  }
}

const someone = new Person(true, 30);
console.log(someone);