[새싹 프론트엔드] 제네릭 타입

Ryu·2022년 12월 16일
0

새싹

목록 보기
32/36

제네릭 타입

제네릭 타입

사용하는 이유

  • 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타입): 반환값타입 { 
		// 코드
}
  • 예시
function printArray<T>(arr: T[]): void {
    console.log(arr);
}

인터페이스와 제네릭

  • 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
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
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주차 블로그 포스팅

0개의 댓글