[TS] TypeScript Generic 사용법

0 0 0

TypeScript 프로젝트라고 들었는데, 막상 시작해 보니 타입이 거의 정의되어 있지 않았습니다. 제가 맡은 플랫폼에서는 타입을 정의하고 작업하기로 규칙을 정해서, 복습하는 마음으로 제네릭을 정리합니다.


제네릭을 사용하는 이유

제네릭은 선언할 때가 아니라 사용할 때 타입을 정해서, 하나의 타입이 아닌 여러 타입에서 동작하도록 만드는 기법입니다.

재사용성이 높아지고 타입 안정성도 유지할 수 있어 더 효율적인 코드를 작성할 수 있습니다.

제네릭 사용법

함수

// 4. generic 타입 =>
function getGeneric<MyType1, MyType2, MyType3>(arg1: MyType1, arg2: MyType2, arg3: MyType3): [MyType3, MyType2, MyType1] {
  if (typeof arg1 === "number") console.log(arg1 + 1000);
  return [arg3, arg2, arg1];
}

const resultGeneric = getGeneric("철수", 123, true);
// function getGeneric<string, number, boolean>(arg1: string, arg2: number, arg3: boolean): [boolean, number, string]

// 5. generic 타입 축약
function getGeneric2<T1, T2, T3>(arg1: T1, arg2: T2, arg3: T3): [T3, T2, T1] {
  if (typeof arg1 === "number") console.log(arg1 + 1000);
  return [arg3, arg2, arg1];
}

const resultGeneric2 = getGeneric2("철수", 123, true);
// function getGeneric2<string, number, boolean>(arg1: string, arg2: number, arg3: boolean): [boolean, number, string]



인터페이스

export interface ISchoolTypes<T = any> {
  name: string;
  class: T;
}

export interface IClassFirstTypes {
  철수: {
    age: number;
    classNum: number;
    grade: number;
    hobby: string;
  };
}

const res: ISchoolTypes<IClassFirstTypes> = {
  name: "aaa",
  class: {
    철수: {
      age: 15,
      classNum: 1,
      grade: 80,
      hobby: "string",
    },
  },
};

댓글 0