본문 바로가기

Typescript

[새싹 프론트엔드] 9주차 - 5 제네릭 타입

제네릭 타입

사용하는 이유

• printArray 함수에 숫자 타입의 배열을 전달

function printArray(arr: number[]): void {
    console.log(arr);
}

const arr1 = [10, 20, 30];
printArray(arr1);

• printArray 함수에 문자열 타입의 배열을 전달

function printArray(arr: number[] | string[]): void {
    console.log(arr);
}

const arr2 = ["a", "b", "c"];
printArray(arr2);

 

• printArray 함수에 불리언 타입의 배열을 전달

function printArray(arr: number[] | string[] | boolean[]): void {
    console.log(arr);
}

const arr3 = [true, false, true];
printArray(arr3);

• printArray 함수가 다양한 타입을 전달 받아 처리하기 위해서는 함수 선언부에 해당 타입을 모두 명시해야 함

• 이런 경우, 제네릭 타입으로 선언하면 함수 선언부를 간단하게 작성 가능

 

제네릭 프로그래밍

• 작성된 코드를 다양한 타입의 객체에 대해 재사용 하는 객체 지향 기법

• 예) 하나의 코드로 숫자, 문자열 등 처리 가능

 

사용 방법

function 함수이름<T>(매개변수: T타입): 반환값타입 {

    // 코드

}

 

* type의 약어 T

예시

function printArray<T>(arr: T[ ]): void {

     console.log(arr);

}

 

 

실습) 제네릭 타입

import React from "react";

const Generic = () => {
  function printArray<T>(arr: T[]): void {
    console.log(arr);
  }

  const arr1 = [10, 20, 30];
  printArray<number>(arr1);

  const arr2 = ["a", "b", "c"];
  printArray<string>(arr2);

  const arr3 = [true, false, true];
  printArray(arr3); //함수 호출 시 타입 생략 가능
  return <div></div>;
};

export default Generic;

 

실행 결과

 

인터페이스와 제네릭

InterfaceGeneric.tsx

const InterfaceGeneric = () => {
    interface UserInterface {
        name : string;
        age: number;
        phone: number | string  //제네릭 이용해서 수정해야할 듯
    }

    const user1: UserInterface = {
        name:"soo",
        age:20,
        phone: "82-10-1234-5678"
    };

    const user2: UserInterface = {
        name: "park",
        age: 30,
        phone: 821012345678
    };
    
    return (
        <div>
            
        </div>
    );
};

export default InterfaceGeneric;

 

InterfaceGeneric.tsx 수정

import React from 'react';

const InterfaceGeneric = () => {
    interface UserInterface<T> {
        name : string;
        age: number;
        phone: T;
    }

    const user1: UserInterface <string> = {
        name:"soo",
        age:20,
        phone: "82-10-1234-5678"
    };

    const user2: UserInterface <number> = {
        name: "park",
        age: 30,
        phone: 821012345678
    };
    
    return (
        <div>
            
        </div>
    );
};

export default InterfaceGeneric;

 

 

ClassGeneric.tsx

import React from 'react';

const ClassGeneric = () => {
    class User<T> {
        constructor(public name: string, public age:number, public phone: T){}
    }

    const user1: User<number> = new User ("soo", 20, 821012345678);
    const user2: User<string> = new User("soo", 20, "82-10-1234-5678");
    
    return (
        <div>
            
        </div>
    );
};

export default ClassGeneric;

 

 

 

 

 

 

 

새싹DT 기업연계형 프론트엔드 실무 프로젝트 과정 9주차 블로그 포스팅