TypeScript Union Types
Union types (Union Types) allow a variable to be set to multiple types via the pipe (|) symbol, and assignment can be made according to the set types.
Note: only the specified types can be assigned; assigning other types will cause an error.
The syntax for creating a union type is as follows:
Type1|Type2|Type3
Example
Declare a union type:
TypeScript
var
val
:
string
|
number
val
=
12
console
.
log
(
"
The number is
"
val
)
val
=
"
Runoob
"
console
.
log
(
"
string is
"
val
)
Compile the above code to get the following JavaScript code:
JavaScript
var
val
;
val
=
12
;
console
.
log
(
"
The number is
"
val
)
;
val
=
"
Runoob
"
;
console
.
log
(
"
string is
"
val
)
;
The output is:
数字为 12
字符串为 Runoob
If you assign another type, an error will be reported:
var val:string|number
val = true
Union types can also be used as function parameters:
TypeScript
function
disp
(
name
:
string
|
string
[
]
)
{
if
(
typeof
name
==
"
string
"
)
{
console
.
log
(
name
)
}
else
{
var
i
;
for
(
i
=
0
;
i
<
name
.
length
;
i
++
)
{
console
.
log
(
name
[
i
]
)
}
}
}
disp
(
"
Runoob
"
)
console
.
log
(
"
Output array....
"
)
disp
(
[
"
Runoob
"
,
"
"
,
"
Taobao
"
,
"
"
]
)
Compile the above code to get the following JavaScript code:
JavaScript
function
disp
(
name
)
{
if
(
typeof
name
==
"
string
"
)
{
console
.
log
(
name
)
;
}
else
{
var
i
;
for
(
i
=
0
;
i
<
name
.
length
;
i
++
)
{
console
.
log
(
name
[
i
]
)
;
}
}
}
disp
(
"
Runoob
"
)
;
console
.
log
(
"
Output array....
"
)
;
disp
(
[
"
Runoob
"
,
"
"
,
"
Taobao
"
,
"
"
]
)
;
The output is:
Runoob
输出数组....
Runoob
Google
Taobao
Facebook
Union type array
We can also declare an array as a union type:
TypeScript
var
arr
:
number
[
]
|
string
[
]
;
var
i
:
number
;
arr
=
[
1
,
2
,
4
]
console
.
log
(
"
Number array
"
)
for
(
i
=
0
;
i
<
arr
.
length
;
i
++
)
{
console
.
log
(
arr
[
i
]
)
}
arr
=
[
"
Runoob
"
,
"
"
,
"
Taobao
"
]
console
.
log
(
"
String array
"
)
for
(
i
=
0
;
i
<
arr
.
length
;
i
++
)
{
console
.
log
(
arr
[
i
]
)
}
Compile the above code to get the following JavaScript code:
JavaScript
var
arr
;
var
i
;
arr
=
[
1
,
2
,
4
]
;
console
.
log
(
"
Number array
"
)
;
for
(
i
=
0
;
i
<
arr
.
length
;
i
++
)
{
console
.
log
(
arr
[
i
]
)
;
}
arr
=
[
"
Runoob
"
,
"
"
,
"
Taobao
"
]
;
console
.
log
(
"
String array
"
)
;
for
(
i
=
0
;
i
<
arr
.
length
;
i
++
)
{
console
.
log
(
arr
[
i
]
)
;
}
The output is:
**数字数组**
1
2
4
String Array
Runoob
Google
Taobao