제너릭을 이용하면 클래스나 함수 인터페이스를 다양한 타입으로 사용할 수 있다.
function getSize(arr: number[] | string[]):number {
return arr.length;
}
const arr1 = [1,2,3];
getSize(arr1); // 3
const arr2 = ["a","b","c"];
getSize(arr2); // 3
.
.
.
const arr3 = [false, true, true]; // boolean[]
getSize(arr3); // 3
const arr4 = [{},{},{name:"Tim"]; // object[]
getSize(arr4); // 3
function getSize<T>(arr: T[]):number {
return arr.length;
}
const arr1 = [1,2,3];
getSize<number>(arr1); // 3
const arr2 = ["a","b","c"];
getSize<string>(arr2); // 3
const arr3 = [false, true, true];
getSize<boolean>(arr3); // 3
const arr4 = [{},{},{name:"Tim"];
getSize<object>(arr4); // 3
interface Mobile {
name: string;
price: number;
option: any; // 어떤 데이터 타입이 들어올지 모르는 상태
}
=>
interface Mobile<T> {
name: string;
price: number;
option: T;
}
인터페이스 & 제너릭을 사용한 객체 만들기
예시 1)
const m1: Mobile<object> = {
name: "s21",
price: 1000,
option: {
color: "red",
coupon: false,
},
};
or
const m1: Mobile< {color: string; coupon: boolean }> = {
name: "s21",
price: 1000,
option: {
color: "red",
coupon: false,
},
};
const m2: Mobile<string> = {
name: "s20",
price: 900,
option: "good",
};
예시 2)
interface User {
name: string;
age: number;
}
interface Car {
name: string;
color: string;
}
interface Book {
price: number;
}
const user: User = { name: "a", age: 10 };
const car: Car = { name: "bmw", color: "red" };
const book: Book = { price: 3000 };
function showName<T>(data:T): string {
return data.name; // 모든 변수에 name이 있다고 장담할 수 없기 때문에 error
}
=> 오류 수정
function showName<T extends {name: string}>(data:T): string {
return data.name;
}
// T 타입은 name 이 string인 객체를 확장한 형태이다. -> showName(book); 은 에러 발생
showName(user);
showName(car);
// showName(book);