클래스, 함수, 인터페이스 를 다양한 타입으로 재사용 가능

코드를 재사용할 수 있다는 측면에서 유용한 수단

 

여러가지 타입을 사용하는 예시

function getSize(arr: number[] | string[] | boolean[]): number{
   return arr.length;
}

const arr1 = [1,2,3];
getSize(arr1)

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

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

 

Generic을 사용한 경우

함수

function getSize<T>(arr: T[]): number{
   return arr.length;
}

const arr4 = [1,2,3];
getSize<number>(arr4)

const arr5 = ["a", "b", "c"];
getSize<string>(arr5)

const arr6 = [true, true, false];
getSize<boolean>(arr6)

 

interface

interface Mobile<T>{
   name: string;
   price: number;
   option: T;
}

const m1: Mobile<object> = {
   name: "s24",
   price: 10000,
   option:{
      color: "red",
      coupon: false,
   }
}

const m2: Mobile<{color: string; coupon: boolean}> = {
   name: "s24",
   price: 10000,
   option:{
      color: "red",
      coupon: false,
   }
}

const m3: Mobile<string> = {
   name: "s24",
   price: 10000,
   option: "good"
}

 

 

특정 인터페이스만 허용하는 함수

interface User{
   name: string;
   age: number;
}

interface Car{
   name: string;
   color: string;
}

interface Book{
   price: number;
}

const user: User = {name: 'a', age: 30};
const car: Car = {name: 'bmw', color: 'red'};
const book: Book = {price: 3000};

function showName<T extends {name: string}>(data:T): string {
   return data.name;
}

showName(user);
showName(car);
showName(book);// name 이 없으모 컴파일 에러 발생

 

참고강의:

https://www.youtube.com/watch?v=pReXmUBjU3E&list=PLZKTXPmaJk8KhKQ_BILr1JKCJbR0EGlx0&index=7

+ Recent posts