AI Reading
Quick summary of this article
TypeScript Union allows a variable to hold more than one data type, solving the limitation of a single fixed type. This feature works with variables, function parameters, and arrays, making code more flexible while keeping type safety.
- A union type is defined using the pipe symbol (|), like
string|number, letting a variable store different types of values. - Union types can be used in function parameters, allowing the function to accept either a single value or an array of values.
- Arrays can also use union types, such as
number[]|string[], to hold either numbers or strings at different times. - The
typeofcheck helps handle union types correctly inside functions by testing the actual data type before processing.
10.TypeScript Union
TypeScript Union So far you have learn that TypeScript is a statically types language where we can define data type of a variable. But, problem is that once you define the data type, you cannot store other value. Also the requirement may arise where we can store more than one data type values. Typescript provides this facility. You can define more than one type of data type for a single variable and then you can store multiple data types values.
Example :
var student_details:string|number
student_details = 50
console.log("Roll Number of the student is : "+student_details)
student_details = "Science"
console.log("He is studying "+student_details)
In the above example, we have declared a variable called ‘students_details’ the variable’s type is union. Now. we have stored roll number as number and then course name as Science which are two different data types and it works fine. Its output is as follows −
In the above example, we have used union type in the variable, but we can also use union type in function also. Below is the example of using union type in the function.
Union Type and function parameter
function students(sname:string|string[]) {
if(typeof sname == "string") {
console.log(sname)
} else {
var i;
for(i = 0;i<sname.length;i++) {
console.log(sname[i])
}
}
}
students("Meena")
console.log("Students names are....")
students(["Rajesh","Kiran","Sudipto","Hetal"])
The output is as follows −
Union Type and Arrays
We have seen so far using union type in variable and functions. Apart from that we can also use union types with arrays, properties and interfaces.
Example: Union Type and Array
var listing:number[]|string[];
var i:number;
listing = [20,30,40,50]
console.log("----- List of numeric Array---") ;
for(i = 0;i<listing.length;i++) {
console.log(list[i])
}
listing = ["Java","PHP","ASP.NET"]
console.log("----- List of string Array---") ;
for(i = 0;i<listing.length;i++) {
console.log(listing[i])
}
In the above program we have declared an array with data type Union Type Numeric and String.Later, we have stored numeric value in the array and displayed. Then, in the same array we have stored string array. Then we printed it. And both worked fine Below is the result :
