내일배움캠프 노드 4기/Today I Learned

[TypeScript] Generic types 제네릭

Milb 2023. 1. 26. 23:26

제네릭 : 선언 시점이 아닌 생성 시점에 타입을 명시하여 하나의 타입만이 아닌 다양한 타입을 사용할 수 있도록 하는 기법

 

제네릭 선언 시 관용적으로 사용하는 식별자

  • T
  • U
  • V

객체

interface MyInterface {
  value: string | number | string[];
}

const stringObject: MyInterface = { value: "hello world!" };
const numberObjecy: MyInterface = { value: 1234 };
const stringArrayObject: MyInterface = { value: ["hello", "world"] };
// 필요한 타입이 생길 때 마다 인터페이스에 추가를 해줘야 해서 불편하다
===================================================================

interface MyInterfaceG<T = string> { // 타입을 미리 지정해둘 수 있다
  value: T;
}

// 각각의 객체에서 필요한 타입을 적용할 수 있다
const stringObjectG: MyInterfaceG = { value: "hello, world!" };
// string 타입이 기초값으로 지정되어 있어 따로 명시해주지 않아도 된다
const numberObjectG: MyInterfaceG<number> = { value: 1234 };
const stringArrayObjectG: MyInterfaceG<Array<string>> = {
  value: ["hello", "world!"],
};