面试题答案
一键面试// 使用接口联合和联合接口描述商品类型结构
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);
上述代码首先定义了 PhysicalProduct
和 DigitalProduct
两个接口分别描述实物商品和虚拟商品的结构,然后通过联合类型 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实现方式没有类型定义,在使用时需要开发者更加注意数据结构的正确性。