DEV Community

Chinwendu Agbaetuo
Chinwendu Agbaetuo

Posted on

2 1 1 1 1

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.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up