Skip to content

联合类型是什么?

参考答案:

在 TypeScript 中,联合类型(Union Types)是一种允许一个变量同时接受多个不同类型值的类型。这种类型通过使用竖线(|)来定义多个可能的类型,表示变量可以是这些类型中的任何一种。

定义联合类型

联合类型的语法是将多个类型用竖线分隔。例如:

typescript
let value: string | number;

在上面的例子中,value 可以是 string 类型或 number 类型的值。

使用联合类型

联合类型非常适合处理一个变量可能有多种不同类型的情况。它允许更灵活的函数参数、返回值和变量类型。

示例 1:函数参数

typescript
function printId(id: number | string) {
  console.log(`The ID is: ${id}`);
}

printId(101);         // 这是一个 number
printId("202");       // 这是一个 string

在这个例子中,printId 函数的参数 id 可以是 numberstring 类型。

示例 2:类型保护

使用联合类型时,你通常需要使用类型保护来确定实际的类型,以便对值进行正确的操作。

typescript
function printLength(value: string | string[]) {
  if (typeof value === 'string') {
    console.log(`Length of string: ${value.length}`);
  } else {
    console.log(`Length of array: ${value.length}`);
  }
}

printLength("Hello, world!"); // 输出: Length of string: 13
printLength(["a", "b", "c"]); // 输出: Length of array: 3

在这个例子中,typeof 操作符用于区分 stringstring[] 类型,并进行相应的处理。

示例 3:对象类型的联合

typescript
type Bird = { type: 'bird'; fly: () => void };
type Fish = { type: 'fish'; swim: () => void };

function move(animal: Bird | Fish) {
  if (animal.type === 'bird') {
    animal.fly();
  } else {
    animal.swim();
  }
}

在这个例子中,move 函数接受 BirdFish 类型的对象。根据对象的 type 属性,函数可以调用相应的方法。

联合类型的优势

  • 灵活性:允许变量、参数或返回值接受多种类型。
  • 类型安全:与普通类型检查和类型保护一起使用,能够确保在编译时捕获潜在的类型错误。

题目要点:

  • 联合类型(Union Types)允许一个变量、参数或返回值接受多种不同的类型,通过使用竖线(|)来定义。
  • 类型保护:使用 typeofinstanceof 或自定义类型保护来确保操作的正确性。
  • 适用场景:适用于处理可能具有多种类型的值或情况。

联合类型提高了代码的灵活性和可维护性,同时保持了类型安全。