MST

星途 面试题库

面试题:TypeScript接口在复杂嵌套对象结构定义及类型推导中的应用

假设有一个复杂的嵌套对象结构,用来表示一个电商订单。订单包含订单基本信息(如订单号、下单时间),订单详情(一个商品数组,每个商品有商品名称、价格、数量),以及收货地址(省、市、区、详细地址)。请使用TypeScript接口准确地定义这个复杂嵌套对象的结构,并编写一个函数,该函数接收这样一个订单对象,计算并返回订单的总金额。同时,解释在这个过程中TypeScript的类型推导机制是如何工作的。
18.3万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
// 定义商品接口
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类型推导机制解释

  1. 函数参数类型推导:当定义 calculateTotal 函数时,参数 order 被明确指定为 Order 类型。TypeScript 能够根据这个类型注解,推导出 order.orderDetailsProduct 类型的数组,order.shippingAddressAddress 类型等。这使得在函数内部访问 order 的属性时,TypeScript 可以进行类型检查,确保代码的类型安全。
  2. 返回值类型推导:在 calculateTotal 函数内部,使用 reduce 方法对 orderDetails 数组进行累加计算总金额。由于 reduce 方法的初始值为 0(类型为 number),并且每次累加的结果也是 number 类型(product.price * product.quantity 的结果为 number),TypeScript 能够根据这个计算过程,推导出函数的返回值类型为 number。即使没有在函数定义时显式指定返回值类型,TypeScript 也能准确地进行类型推导。

这样,通过明确的接口定义和类型推导机制,TypeScript 能有效地帮助开发者编写类型安全的代码,减少潜在的运行时错误。