📜  打字稿联盟

📅  最后修改于: 2022-05-13 01:56:56.113000             🧑  作者: Mango

打字稿联盟

TypeScript union 能够组合一种或两种不同类型的数据(即数字、字符串、浮点数、双精度等)。这是表达具有多种类型的变量的最强大的方式。使用竖线('|')符号将两种或多种数据类型组合起来,实现联合类型。

句法:

(type1|type2|type3|...|type-n)

例子:

let value: number | string;  
value = 190;  
console.log("Numeric value of the value: " + value);  
value = "Welcome to TypeScript!";  
console.log("String value of the value: " + value);

编译上述代码以生成以下 JavaScript 代码。

let value: number | string;  
value = 190;  
console.log("Numeric value of the value: "+value);  
value = "Welcome to TypeScript!";  
console.log("String value of the value: "+value); 

输出:

190
Welcome to TypeScript!

示例:在此示例中,极客属于联合类型,使用 (字符串 | number) 表示。所以,我们可以给它分配一个字符串或一个数字,其他的都是不允许的。

let geeks: (string | number);
geeks = 123;   // OK
geeks = "XYZ"; // OK
geeks = true;  // Compiler Error 

函数参数作为联合类型:我们可以将函数作为参数传递。在本例中,参数 geeks 属于联合类型。您可以传递字符串值或数字值,否则编译器会出错。
例子:

function displayType(geeks: (string | number)) {
    if(typeof(geeks) === "number")
        console.log('geeks is number.')
    else if(typeof(geeks) === "string")
        console.log('geeks is string.')
}
  
// Output: Code is number. 
displayType(49); 
  
// Output: Code is string.
displayType("GFG"); 
  
// Compiler Error: Argument of type 'true' is not 
// assignable to a parameter of type string | number
displayType(true); 

数组作为联合类型:在联合类型中,我们也可以传递一个数组。该程序声明了一个数组。该数组可以表示数字集合或字符串集合。
例子:

//Generated by typescript 1.8.10
var arr = [2, 5, 7, 5, 11, 15];
  
console.log("Display the array elements");
  
// Loop to display array elements
for (var i = 0; i < arr.length; i++) {
   console.log(arr[i]);
}
  
// Declare another array
arr = ["Geeks", "G4G", "GFG", "GeeksforGeeks"];
  
console.log("Display the array elements");
  
// Loop to display the array elements
for (var i = 0; i < arr.length; i++) {
   console.log(arr[i]);
}

输出:

Display the array elements
2
5
7
5
11
15
Display the array elements
Geeks
G4G
GFG
GeeksforGeeks

Union 可以替换枚举:它是由Enums创建的常量类型列表。默认情况下,枚举具有索引值(0、1、2、3 等)。枚举实际上被转译(获取以一种语言编写的源代码并转换为具有相似抽象级别的另一种语言)并最终生成像 JavaScript 这样的结果。