《TypeScript》 - 联合类型
发布时间:2022-09-30 16:37:27 317 相关标签:
联合类型(Union Types)可以通过管道(|)将变量设置多种类型,赋值时可以根据设置的类型来赋值。
有些时候,我们对类型的期待可能并不希望只是单纯的一种,也不希望是所有类型,而是某几种类型,这个时候就需要使用联合类型。例如时间,我们可能有时无论是数字类型还是字符串类型,我们都可以接受。
注意:只能赋值指定的类型,如果赋值其它类型就会报错。
创建联合类型的语法格式如下:
代码示例:
// 变量
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.
文章来源: https://blog.51cto.com/u_11071029/5641177
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报