MST

星途 面试题库

面试题:TypeScript接口联合与联合接口在复杂类型中的应用

假设有一个电商系统,商品可能是实物商品(具有重量、尺寸属性)或者虚拟商品(具有下载链接属性)。请使用接口联合和联合接口来准确描述商品的类型结构,并编写一个函数,该函数接受一个商品对象作为参数,根据商品类型执行不同的操作(比如打印实物商品的重量和尺寸,打印虚拟商品的下载链接)。
42.6万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
// 使用接口联合和联合接口描述商品类型结构
interface PhysicalProduct {
  type: 'physical';
  weight: number;
  size: string;
}

interface DigitalProduct {
  type: 'digital';
  downloadLink: string;
}

type Product = PhysicalProduct | DigitalProduct;

// 定义函数根据商品类型执行不同操作
function handleProduct(product: Product) {
  if (product.type === 'physical') {
    console.log(`实物商品 - 重量: ${product.weight}, 尺寸: ${product.size}`);
  } else {
    console.log(`虚拟商品 - 下载链接: ${product.downloadLink}`);
  }
}

你可以这样调用函数:

// 测试函数
const physicalProduct: PhysicalProduct = {
  type: 'physical',
  weight: 1.5,
  size: '10cm x 20cm'
};

const digitalProduct: DigitalProduct = {
  type: 'digital',
  downloadLink: 'https://example.com/download'
};

handleProduct(physicalProduct);
handleProduct(digitalProduct);

上述代码首先定义了 PhysicalProductDigitalProduct 两个接口分别描述实物商品和虚拟商品的结构,然后通过联合类型 Product 将两种商品类型联合起来。handleProduct 函数根据传入商品对象的 type 属性来执行不同的操作。最后通过两个示例对象调用该函数进行测试。

这里以TypeScript为例进行编写,在JavaScript中没有类型定义,实现方式略有不同,但基本逻辑类似。若要在JavaScript中实现,可以使用如下方式:

function handleProduct(product) {
  if (product.type === 'physical') {
    console.log(`实物商品 - 重量: ${product.weight}, 尺寸: ${product.size}`);
  } else {
    console.log(`虚拟商品 - 下载链接: ${product.downloadLink}`);
  }
}

// 测试函数
const physicalProduct = {
  type: 'physical',
  weight: 1.5,
  size: '10cm x 20cm'
};

const digitalProduct = {
  type: 'digital',
  downloadLink: 'https://example.com/download'
};

handleProduct(physicalProduct);
handleProduct(digitalProduct);

这种JavaScript实现方式没有类型定义,在使用时需要开发者更加注意数据结构的正确性。