function loggingIdentity<T>(table: T[]): string {
return `Total elements in the table: ${table.length}`;
}
Constraints
type Product = { id: number; name: string; price: number };
function getTotal<T extends Product>(products: T[]): string {
const totalPrice = products.reduce((sum, p) => sum + p.price, 0);
return `There are ${products.length} products. And the total price is ${totalPrice}.`;
}
Parameter Defaults
type ApiResponse<T = string> = { data: T; success: boolean; };
const response1: ApiResponse = { data: "OK", success: true };
const response2: ApiResponse<number> = { data: 200, success: true };
TypeScript: Documentation - Generics