TypeScript tutorial: Lesson 11 – Union Type


Syntax:

type1|type2|type3 

Example 1: Union Type variable:

var val:string|number //this variable can has type string or number
val = 1986 
console.log("numeric value of val "+val) 
val = "This is a string" 
console.log("string value of val "+val)

Result:

[LOG]: numeric value of val 1986 
[LOG]: string value of val This is a string 

Example 2: Union Type and function parameter

function sum(values:string|number[]):number{    
    if(typeof values == "string"){
        return values.split(",").map(parseFloat).reduce((a,b)=>(a+b))
    }else{
        return values.reduce((a,b)=>(a+b))
    }
}
console.log(sum([1,2]))
console.log(sum("1,2"))

Result:

[LOG]: 3 
[LOG]: 3 

Example 3: Union Type and Array

var arr:string[]|number[]
arr = [1990,1986] 
console.log("numeric values of arr "+arr) 
arr = ["tutorialspots",".com"]
console.log("string values of arr "+arr)

Result:

[LOG]: numeric values of arr 1990,1986 
[LOG]: string values of arr tutorialspots,.com 

Leave a Reply