남과 같이 해선 남 이상이 될 수 없다.

TypeScript

TypeScript - generic

맨동 2021. 6. 22. 18:52
728x90

Generic 이란?

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

 

any VS generic

  • 제네릭과 함께 any도 유연한 타입에 속합니다. 하지만 any로 타입을 정의하면 어떤 값이든 올 수 있어 안정성이 떨어집니다. (들어오는 값에 따라 타입 추론을 하기 때문입니다.)
  • any처럼 유연하게 여러 타입을 받으면서 안정성을 지키고 싶을 때 제네릭을 사용합니다.

사용법

// 1. 어떤 타입을 받을 건지 먼저 정의 (check<T>)
// 2. params 타입으로 정의 (text: T)
function logText<T>(text: T): T {
  console.log(text);
  return text;
}
// 3. 함수를 호출할때 타입 정의
const str = check<string>("check");
str.length; // string 이기 때문에 length 가능

check<boolean>(true); // type: boolean
check<string>("Hello"); //type: string
check<number>(365); //type: number

 

Generic Array

//배열
function identity <T> (arg: Array<T>) : Array<T> {
    return arg;
}

console.log(identity <string> (['abc', 'def']));

 

Generic 타입 제한

 

extends를 사용하여 특정 메서드를 가진 타입으로만 가능하도록 제한할 수 있습니다.

아래코드는 length 메서드가 있는 타입만 지정할 수 있도록 generic을 제한합니다.

interface LengthType {
  length: number;
}

function TextLenghth<T extends LengthType>(text: T): number {
  return text.length;
}

keyof

 

keyof 를 사용하면 특정 객체의 키값만을 T로 넣을 수 있게할 수 있습니다.

interface Fruit {
  name: string;
  price: number;
}

// ShoppingItem의 키 중에서 한가지가 Generic이 된다.
function getFruit<T extends keyof Fruit>(fruitItem: T): T {
  return fruitItem;
}

console.log(getFruit("name"));
console.log(getFruit("price")); 

//name
//price
728x90

'TypeScript' 카테고리의 다른 글

[TypeScript] Property '...' does not exist on type 'DefaultRootState' - Redux type Error  (0) 2022.03.06
2021/06/22 TypeScript  (0) 2021.06.22
2021/06/21 TypeScript  (0) 2021.06.21
2021/06/19 TypeScript  (0) 2021.06.19
2021/06/17 TypeScript  (0) 2021.06.17