Union Of Scripts

Union Of Scripts

Understanding Unions In Typescript

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
  • score can 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
}
  • FirstUser uses the union data type to combine User and Admin data types.

  • If any type is added to FirstUser without being specified in any of the earlier type aliases, User and Admin, 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:...`)
}
  • getUserID function has an id parameter 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
}
  • getUserID takes in an id parameter that can either be a string or a number, but how come calling id.toLowerCase returns an error?

  • This is because the id parameter can be a string, and then be changed to a number later on in the function. Hence, calling a string method on id is correct if id is a string, but due to the fact that id can 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
  • type1 and type2 are 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[] and number[] data types together, but this only directs the code that all the array contents in type3 should either be all strings or all numbers but cannot be mixed. *type4 is 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.