개발공부/개념정리 | TypeScript

제네릭

개발집사 2022. 12. 26. 16:24

정의

함수를 파라미터처럼 사용하는 것.

기본 문법
function logText<T>(text: T): T {
  console.log(text);
  return text;
}


logText<string>('hi');

 

❗️유니온 방식을 이용한 제네릭 타입의 문제점
function logText(text: string | number) {
  console.log(text);
  return text;
}

const a = logText('hi');
a.split('');
logText(10);

코드를 위와 같이 작성했을때 split은 에러가 난다. 에러코드를 살펴보자면 아래와 같이 string에서는 가능하지만 number 형식에서는 사용이 불가능하다는 문구가 나타나게된다.

 

 

제네릭의 타입추론에서의 이점

확실하게 어떤 타입인지 선언해주기때문에 정확성이 올라간다.

function logText<T>(text: T): T {
  console.log(text);
  return text;
}

const str = logText<string>('abc');
str.split('');
const ligin = logText<boolean>(true);

 

인터페이스에 제네릭을 선언하는 방법
interface Dropdown<T> {
  value: T;
  selected: boolean;
}

const obj: Dropdown<string> = { value: 'abc', selected: false };
const num: Dropdown<number> = { value: 102, selected: true };

 

제네릭의 타입 제한
function logTextLength<T>(text: T[]): T[] {
  console.log(text.length);
  text.forEach(function(text){
    console.log(text);
  })
  return text;
}
logTextLength<string>(['hi', 'abc']);
interface LengthType {
  length: number;
}

function logTextLength<T extends LengthType>(text: T): T {
  text.length;
  return text;
}
logTextLength(10); //error => 'number' 형식의 인수는 'LengthType' 형식의 매개 변수에 할당될 수 없습니다.
logTextLength({length: 10});

 

typeof를 이용한 타입 제한
interface ShoppingItem {
  name: string;
  price: number;
  stock: number;
}

function getShoppingItemOption<T extends keyof ShoppingItem>(itemOption: T): T {
  return itemOption;
}
getShoppingItemOption(10); //error
getShoppingItemOption<string>('a'); //error
getShoppingItemOption('name');
getShoppingItemOption('price');

 

'개발공부 > 개념정리 | TypeScript' 카테고리의 다른 글

이넘(Enums)  (0) 2022.12.23
Union type | intersection type  (0) 2022.12.23
인터페이스 / 타입 별칭  (0) 2022.12.22
기본 타입 && 함수타입  (0) 2022.12.21
기초설정  (0) 2022.12.21