TypeScript Unlocked: Union

TypeScript Unlocked: Union

·

2 min read

💡
This article is a part of TypeScript Unlocked Series on my blog. Every article in the series is short, crisp and filled with examples and code snippets. If you want to learn TypeScript from scratch for absolutely FREE!!! check it out.

Union enables us to assign two types to a single variable. Sometimes there might arise a situation where we might not know what kind of data will be encountering. In this kind of situation union comes in very handy. syntax for union is fairy straight forward we just use a pipe | between two types.

let height : number | string // value can either be a number of a string
height = 5.2
height = "5 foot 2 inches"

Union in functions

It is very common scenario to use unions in functions. in the example below we are specifying that middle name should wither be string or null but one thing to consider here is we have applied a condition to first check if middle name is not null before calling toUpperCase method. if we did not do it TypeScript would have given us an error.

function getFullName(firstName:string, middleName : string | null, lastName : string): string {
    if (middleName)
        return `${firstName.toUpperCase()} ${middleName.toUpperCase()} ${lastName.toUpperCase()}`
    else
        return `${firstName.toUpperCase()} ${lastName.toUpperCase()}`
 }

we can also make use of Union with type aliases

type User = {
    firstName:string
    middleName : string | null
    lastName : string
}

Using Unions in Arrays

let ages1 : number[] | string[] = [22,24,25] // array can either be of number or string
let ages2 : number[] | string[] = ["22","24","25"] // array can either be of number or string

let ages5 : (number | string)[] = [22,24,"25"] // array elements can be both
let ages3 : Array<number | string> = [22,24,"25"] // Another way of achieving the same results

it works pretty much same in arrays as well. So this is almost everything you have to know about Union in TypeScript for you day to day stuff but if you are more curious and want some more details you can visit the Official Docs

if you reached till here and you liked what you read don't forget LIKE to SHARE it with other people. if you have any feedback or suggestions feel free to use the comment section. Hope you tag along till the end of this series and strengthen your coding armor by adding TypeScript to it. Happy coding!

Â