面试题答案
一键面试// 定义商品接口
interface Product {
name: string;
price: number;
quantity: number;
}
// 定义收货地址接口
interface Address {
province: string;
city: string;
district: string;
detail: string;
}
// 定义订单接口
interface Order {
orderNumber: string;
orderTime: string;
orderDetails: Product[];
shippingAddress: Address;
}
// 计算订单总金额的函数
function calculateTotal(order: Order): number {
return order.orderDetails.reduce((total, product) => {
return total + product.price * product.quantity;
}, 0);
}
TypeScript类型推导机制解释
- 函数参数类型推导:当定义
calculateTotal
函数时,参数order
被明确指定为Order
类型。TypeScript 能够根据这个类型注解,推导出order.orderDetails
是Product
类型的数组,order.shippingAddress
是Address
类型等。这使得在函数内部访问order
的属性时,TypeScript 可以进行类型检查,确保代码的类型安全。 - 返回值类型推导:在
calculateTotal
函数内部,使用reduce
方法对orderDetails
数组进行累加计算总金额。由于reduce
方法的初始值为0
(类型为number
),并且每次累加的结果也是number
类型(product.price * product.quantity
的结果为number
),TypeScript 能够根据这个计算过程,推导出函数的返回值类型为number
。即使没有在函数定义时显式指定返回值类型,TypeScript 也能准确地进行类型推导。
这样,通过明确的接口定义和类型推导机制,TypeScript 能有效地帮助开发者编写类型安全的代码,减少潜在的运行时错误。