TypeScript Union Types

Union Types allow variables to be set to multiple types using the pipe (|) symbol, and values can be assigned 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 = "Example" console.log("The 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 = "Example"; console.log("The string is" + val);

The output result is:

数字为 12
字符串为 Example

Assigning other types will cause an error:

var val:string|number 
val = true 

You can also use union types 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("Example") console.log("Output array....") disp(["Example","Google","Taobao","Facebook"])

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("Example"); console.log("Output array...."); disp(["Example", "Google", "Taobao", "Facebook"]);

The output result is:

Example
输出数组....
Example
Google
Taobao
Facebook

Union Type Arrays

We can also declare arrays as union types:

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 = ["Example","Google","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 = ["Example", "Google", "Taobao"]; console.log("**String array**"); for (i = 0; i < arr.length; i++) { console.log(arr[i]); }

The output result is:

**数字数组**
1
2
4
**字符串数组**
Example
Google
Taobao
Other Extensions