Union Of Scripts
Understanding Unions In Typescript

Life is becoming more interesting every day...
Currently, I am invested in being a better backend engineer, and also a medical doctor in training.
I have a keen interest in cloud engineering, biotechnology and molecular biology, and a fascination with VR.
In my free time, I enjoy reading, playing strategy games, experiencing music, and exploring philosophy.
cover photo credit: Ismail Aghazada
Introduction
To ensure that you understand how to use every TS feature discussed in this series, it is important I keep all articles lazer-focused on the issue of discussion, and it may result in the articles being too short or too long, or just right. For today, I will explore the Union type feature and its intricasies.
Union of What?
Union is a data type that allows you specify that a model can have two or more combinations of types. Union makes this possible with a pipe | sign syntax, like below:
let score: number | string = 33
score = 44
score = true // throws in an error
scorecan be a number or a string, but if a boolean data type is referenced to it, it will throw an error
The Union type can also be used to combine type aliases alongside data types:
type User = {
name: string;
id: number
}
type Admin = {
username: string;
id: number
}
let FirstUser: User | Admin = {
name : "Kelvin",
id : 763
}
FirstUseruses the union data type to combineUserandAdmindata types.If any type is added to
FirstUserwithout being specified in any of the earlier type aliases,UserandAdmin, Typescript(TS) static checking throws in an error.
Union Functions
Most times when working with large code bases, correctly describing what the function can take in as a parameter, or what it can return can prevent life-threatening bugs from popping up in your code base.
function getUserID(id : number | string){
console.log(`${id} is this, and so here is your Reg no:...`)
}
getUserIDfunction has anidparameter that could either be a string or a number.
Using Union types in our functions also presents a minimal issue.
function getUserID (id : number | string){
console.log(`${id} is this, and so here is your Reg no:...`)
id.toLowerCase() // Triggers an error
}
getUserIDtakes in anidparameter that can either be a string or a number, but how come callingid.toLowerCasereturns an error?This is because the
idparameter can be a string, and then be changed to a number later on in the function. Hence, calling a string method onidis correct ifidis a string, but due to the fact thatidcan later become a number will definitely lead to errors, since string methods cannot work on numbers.The solution here is to specify the methods on these functions using conditionals:
function getUserID (id : number | string){
console.log(`${id} is this, and so here is your Reg no:...`)
if(typeof id === "string"){
id.toLowerCase()
}
}
Unions in arrays
This is how to specify the content of arrays:
const type1 : string[] = ["su","siuu","siuuu"]
const type2 : number[] = [2,3,4,5]
const type3 : string[] | number[] = ["fdsa","lfdha",4] // error
const type4 : (string | number)[] = ["fdsa","lfdha",4] // correct
type1andtype2are the normal ways of describing arrays that should have one data type of content.To use the union data type for arrays, you may try to combine both
string[]andnumber[]data types together, but this only directs the code that all the array contents intype3should either be all strings or all numbers but cannot be mixed. *type4is the way to correctly enable an array have any type of content with different data types in it at an instance.
Conclusion
Understanding and correctly implementing TypeScript's Union types is crucial for creating robust and error-free code. The Union type allows for flexible data type combinations, enhancing the adaptability of your models and functions. However, careful consideration is required to avoid common pitfalls, such as method mismatches when handling mixed types. By leveraging Union types effectively, you can write more versatile and safer code, especially in complex projects with varying data requirements.




