// 定义Product接口
interface Product {
id: string;
name: string;
price: number;
}
// 定义User接口
interface User {
id: string;
name: string;
email: string;
}
// 定义Order接口
interface Order {
id: string;
product: Product;
user: User;
quantity: number;
}
// 定义处理器函数的类型约束
type OrderProcessor<T> = (order: Order) => T;
// 实现泛型函数processOrder
function processOrder<T>(orders: Order[], processor: OrderProcessor<T>): T[] {
return orders.map(processor);
}
// 示例处理器函数:计算订单总价
const calculateTotalPrice: OrderProcessor<number> = (order) => {
return order.product.price * order.quantity;
};
// 使用示例
const orders: Order[] = [
{
id: '1',
product: { id: 'p1', name: '商品1', price: 10 },
user: { id: 'u1', name: '用户1', email: 'user1@example.com' },
quantity: 2
},
{
id: '2',
product: { id: 'p2', name: '商品2', price: 15 },
user: { id: 'u2', name: '用户2', email: 'user2@example.com' },
quantity: 3
}
];
const totalPrices = processOrder(orders, calculateTotalPrice);
console.log(totalPrices); // 输出: [20, 45]