上一章TypeScript教程请查看:TypeScript元组用法和操作
在TypeScript中,我们可以定义一个具有多种类型值的变,换句话说,TypeScript可以组合一到两种不同类型的数据。在一个单一类型中,它被称为union联合类型,联合类型是用多种类型表示变量的强大方法,我们可以在类型之间使用管道(‘|’)符号组合两个或多个数据类型。
语法
(type1 | type2 | type3 | ........ | type-n)
例子
let value: number|string;
value = 120;
console.log("数值value: "+value);
value = "Welcome to srcmini";
console.log("字符串value: "+value);
在函数参数中传递联合类型
在函数中,可以将union类型作为参数传递。我们可以从下面的例子中理解它。
例子
function display(value: (number | string))
{
if(typeof(value) === "number")
console.log('value为number类型.');
else if(typeof(value) === "string")
console.log('value为string类型.');
}
display(123);
display("ABC");
将联合类型传递给数组
TypeScript允许将联合类型传递给数组,我们可以从下面的例子中理解它。
例子
let arrType:number[]|string[];
let i:number;
arrType = [1,2,3,4];
console.log("数值类型数组:")
for(i = 0;i<arrType.length;i++){
console.log(arrType[i]);
}
arrType = ["UK","America","Ireland"];
console.log("字符串类型数组:")
for(i = 0;i<arrType.length;i++){
console.log(arrType[i]);
}
联合类型替换枚举类型
枚举用于创建包含常量列表的类型。默认情况下,枚举有索引值(0、1、2、3等)。我们可以在下面的示例中看到枚举,它包含颜色列表。
例子
export enum Color {RED, BLUE, WHITE}
我们可以使用union类型而不是enum,并且可以以更短的方式获得类似的好处。
例子
export type Color = 'red' | 'white' | 'blue';
const myColor: Color = 'red';
console.log(myColor.toUpperCase());
评论前必须登录!
注册