클래스, 함수, 인터페이스를 다양한 타입으로 재사용 가능
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<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",
};
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 };
// name이 제네릭 T에 들어있지 않기 때문에 extends로 상속
// 제네릭T는 name을 항상 가진다는 뜻
function showName<T extends { name: string }>(data: T): string {
return data.name;
}
showName(user);
showName(car);
showName(book);
'Frontend > TypeScript' 카테고리의 다른 글
[TypeScript] 사용하지 않는 변수와 파라미터로 인한 빌드 실패문제 해결 방법 (0) | 2025.05.28 |
---|---|
[TypeScript] 유틸리티 타입 (0) | 2024.08.13 |
[TypeScript] 클래스 (0) | 2024.08.13 |
[TypeScript] 리터럴, 유니온/교차 타입 (0) | 2024.08.13 |
[TypeScript] 함수 (0) | 2024.08.13 |