定义联合类型

您可能会看到的第一种组合类型的方法是联合类型。 联合类型是由两种或多种其他类型组成的类型,表示可能是这些类型中的任何一种的值。 我们将这些类型中的每一种都称为联合的成员。

The first way to combine types you might see is a union type. A union type is a type formed from two or more other types, representing values that may be any one of those types. We refer to each of these types as the union's members.

ujK+eDXA9Vr/0SoZRtSWmaYB8dizEYNkyPa86LyYH99uZjfd5QVhBqGgBBn3aFiaFPLcOMRMKKNzGagH1ggpTFkXCensk3RcGB8bz6W9cJN184F8RHY8IrPC+YzoaZzjwLaZI50xznV0ISf5E/QWEi5Lx2yimE2Hx2BktVeWoTS1gpZpLdqfD4Ek7jabn3JfkRY/S8pYU1Youjpgo1/vkQ==

function printId(id: number | string) {
  console.log("Your ID is: " + id);
}
// OK
printId(101);
// OK
printId("202");
// Error
printId({ myID: 22342 });