MST
星途 面试题库

面试题:TypeScript 联合类型与交叉类型的基础应用

请解释 TypeScript 中联合类型与交叉类型的定义,并各举一个实际应用场景的代码示例。假设你要定义一个函数,它接受一个参数,该参数可以是字符串或者数字,并且根据传入参数的类型返回不同的结果,使用联合类型实现该函数。
33.3万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试

联合类型定义

联合类型表示一个值可以是几种类型之一。使用 | 分隔不同的类型。

交叉类型定义

交叉类型是将多个类型合并为一个类型。它包含了所需的所有类型的特性,使用 & 连接。

联合类型实际应用场景代码示例

function printValue(value: string | number) {
    if (typeof value === 'string') {
        return `The string is: ${value}`;
    } else {
        return `The number is: ${value}`;
    }
}

console.log(printValue('hello')); 
console.log(printValue(42)); 

交叉类型实际应用场景代码示例

interface A {
    a: string;
}
interface B {
    b: number;
}

function printAB(obj: A & B) {
    console.log(`a: ${obj.a}, b: ${obj.b}`);
}

let abObj: A & B = {a: 'test', b: 123};
printAB(abObj);