DEV Community

Chinwendu Agbaetuo
Chinwendu Agbaetuo

Posted on

Union Types in TypeScript

After immersing myself in TypeScript for three years and actively writing production code, I've encountered challenges grappling with its various terminologies and contextual nuances. I aim to assist you in grasping these concepts better, sharing the insights I've gained along the way.

Typescript has three primitive types: string, number and boolean. Sometimes, we have arguments of two or more other types.

const ticketId = "a57pdnhkl23A" | 3745959

// Ticket Id can be a number or a string 
Enter fullscreen mode Exit fullscreen mode

Let's write a function that displays the ticket Id in the console.

function printTicketId(ticketId: number | string) {
   console.log(id.toLocaleLowerCase());
}
Enter fullscreen mode Exit fullscreen mode

TypeScript will raise an error for the code block, indicating that the property toLocaleLowerCase() is exclusive to a specific member within the Union type, specifically, the string. The error message will be something along these lines.

Property 'toLocaleLowerCase' does not exist on type 'string | number'. 
Property 'toLocaleLowerCase' does not exist on type 'number'.
Enter fullscreen mode Exit fullscreen mode

To address this issue, we're bringing in a helpful concept called narrowing. This approach allows us to effectively manage scenarios involving both strings and numbers.

function printTicketId(ticketId: number | string) {
  if (typeof ticketId === "string") {
    console.log(`{Your ticket id is ${ticketId.toUpperCase()}`);
  } else {
    console.log(`{Your ticket id is ${ticketId}`);
  }
}
Enter fullscreen mode Exit fullscreen mode

After incorporating the code block above, the error has vanished. This marks the beginning of a series of posts dedicated to TypeScript, as I embark on a journey to enhance my skills with this type-safe language.

Top comments (0)