TypeScript Union

A TypeScript Union variable can hold a value that belongs to one of the many declared datatypes.

Syntax of TypeScript Union

To specify the different datatypes that a union variable can hold, use the following syntax:

</>
Copy
 var varname: datatype1|datatype2|datatype3
  • var is the keyword
  • varname is the name of the union variable
  • datatype1, datatype2, . .  datatypes that the variable can hold should be separated by vertical bar

Example

Following is an example of TypeScript Union, where a variable can hold data of either number or string.

example.ts

</>
Copy
var ns : number|string
ns = 25
console.log("type of ns is : "+(typeof ns))
console.log("value of ns : "+ns)
ns = "Twenty Five"
console.log("\ntype of ns is : "+(typeof ns))
console.log("value of ns : "+ns)

On traspiling the code, following JavaScript is generated.

example.js

</>
Copy
var ns;
ns = 25;
console.log("type of ns is : " + (typeof ns));
console.log("value of ns : " + ns);
ns = "Twenty Five";
console.log("\ntype of ns is : " + (typeof ns));
console.log("value of ns : " + ns);

Output

type of ns is : number
value of ns : 25
type of ns is : string
value of ns : Twenty Five

Union Type with Arrays

Even TypeScript Array can be declared as union type variable, i.e., the array variable can hold array of elements that belong to any a given set of datatypes.

Example

In the following example, variable b is declared as a union type variable that can hold either a number or number array.

example.ts

</>
Copy
var a : number
var b : number|number[]
a = 10
b = 5
var c = a + b
console.log("sum of a and b : "+c)
b = [4, 8, 9, 1, 5, 6]
var c = a
b.forEach(i => {
    c = c+i
})
console.log("sum of a and b : "+c)

When traspiled to JavaScript, following .js file is generated.

example.js

</>
Copy
var a;
var b;
a = 10;
b = 5;
var c = a + b;
console.log("sum of a and b : " + c);
b = [4, 8, 9, 1, 5, 6];
var c = a;
b.forEach(function (i) {
    c = c + i;
});
console.log("sum of a and b : " + c);

Output

sum of a and b : 15
sum of a and b : 43

Conclusion

In this TypeScript TutorialTypeScript Union, we have learnt how to declare a variable as union type. We also looked into the declaration of array variables as union type.