🌈 코딩앙마의
TypeScript 강좌
수강 후, 이해한 내용을 정리한 글입니다.
제네릭은 일반적으로 T
로 나타낸다.
// 📍 제네릭 사용 전
function getSize(arr: number[] | string[] | boolean[] | object[]): 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];
getSize(arr3); // 3
const arr1 = [{}, {}, { name: "Tim" }];
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 arr1 = [{}, {}, { name: "Tim" }];
getSize<object>(arr4); // 3
interface Mobile<T> {
name: string;
price: number;
option: T;
}
const m1: Mobile<object> = {
name: "s21",
price: 1000,
option: {
color: "red",
coupon: false,
},
};
const m2: Mobile<string> = {
name: "s20",
price: 900,
option: "good",
};
extends를 사용하여 제네릭으로 정의된 object types의 필수 키와 타입을 지정할 수 있다.
interface User {
name: string;
age: number;
}
interface Car {
name: boolean;
color: string;
}
interface Book {
price: number;
}
const user: User = { name: "a", age: 10 };
const car: Car = { name: true, color: "red" };
const book: Book = { price: 3000 };
// T는 name(string type)이 있는 object types를 확장한 형태이다.
// → name이 없거나, string type이 아니라면 error
function showName<T extends { name: string }>(data: T): string {
return data.name;
}
showName(user); // ✅
showName(car); // ❌ Error! name이 string type이 아님
showName(book); // ❌ Error! name이 없음