Skip to content

联合类型是什么?

Posted on:2024年9月5日 at 01:17

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

定义联合类型

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

let value: string | number;

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

使用联合类型

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

示例 1:函数参数

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

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

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

示例 2:类型保护

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

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:对象类型的联合

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 属性,函数可以调用相应的方法。

联合类型的优势

原文转自:https://fe.ecool.fun/topic/4d9c10d8-6509-4675-ba54-86c34d7116b4