返回

《TypeScript》 - 联合类型

发布时间:2022-09-30 16:37:27 317

联合类型(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.
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(0)
按点赞数排序
用户头像
精选文章
thumb 中国研究员首次曝光美国国安局顶级后门—“方程式组织”
thumb 俄乌线上战争,网络攻击弥漫着数字硝烟
thumb 从网络安全角度了解俄罗斯入侵乌克兰的相关事件时间线
下一篇
JavaScript练习 - promise转async/await 2022-09-30 16:05:56