《TypeScript》 - 联合类型
2021-07-04 本文已影响0人
张中华
联合类型(Union Types)可以通过管道(|)将变量设置多种类型,赋值时可以根据设置的类型来赋值。
有些时候,我们对类型的期待可能并不希望只是单纯的一种,也不希望是所有类型,而是某几种类型,这个时候就需要使用联合类型。例如时间,我们可能有时无论是数字类型还是字符串类型,我们都可以接受。
注意:只能赋值指定的类型,如果赋值其它类型就会报错。
创建联合类型的语法格式如下:
Type1|Type2|Type3
代码示例:
// 变量
const variable: string | number = 10;
function print(value:string|number):void;
function print(value:string|number):string|number;
// 方法参数
function print(value:string|number) {
if(typeof value === 'string') {
console.log(`${value} type is string.`);
} else {
console.log(`${value} type is number.`);
}
}
print('hello world'); // hello world type is string.
print(10); // 10 type is number.
// 方法返回值
function print(value:string|number):string|number {
if(typeof value === 'string') {
console.log(`${value} type is string.`);
return 'string'
} else {
console.log(`${value} type is number.`);
return 0;
}
}
print('hello world'); // hello world type is string.
print(10); // 10 type is number.