TypeScript Generic

김정현·2022년 5월 3일
0

TypeScript

목록 보기
5/12

Genenric

function helloBasic<T, U>(message: T, comment: U): T {
  return message;
}

helloBasic<string, number>("KIM", 27); // 지정
helloBasic(36, 39); // T와 U가 추론이 된다

Generic Array

function helloArray<T>(message: T[]): T {
  return message[0];
}

helloArray(["Hello", "World"]);
function helloTuple<T, K>(message: [T, K]): T {
  return message[0];
}

helloTuple(["Hello", "World"]);
helloTuple(["Hello", 5]);

Generic Function

// type Alias 표현
type HelloFunctionGeneric1 = <T>(message: T) => T;
const helloFunction1: HelloFunctionGeneric1 = <T>(message: T): T => {
  return message;
};

// interface 표현
interface HelloFunctionGeneric2 { 
  <T>(message: T): T;
}

const helloFunction2: HelloFunctionGeneric2 = <T>(message: T): T => {
  return message;
};

Generic class

class Person<T, U> {
  private _name: T;
  private _age: U;

  constructor(name: T, age: U) {
    this._name = name;
    this._age = age;
  }
}

new Person("KJH", 27);
new Person<string, number>("KJH", 27);

Generics with extends

// T 는 string 또는 number 만 가능(extends를 사용해서)
class PersonExtends<T extends string | number> {
  private _name: T;

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

new PersonExtends("KJH")
new PersonExtends(27)
new PersonExtends(true) // boolean타입이라서 에러가 난다.
profile
개발일지

0개의 댓글