DEV Community

JianTeng
JianTeng

Posted on

Checking union types in Typescript

It is a common use case where we check for multiple strings matches in if statements, as shown in the example below.

const exampleMovement: string = '';

if (exampleMovement === 'up' || exampleMovement === 'down' || exampleMovement === 'left' || exampleMovement === 'right') {
    // application logic
}
Enter fullscreen mode Exit fullscreen mode

We can clean it up by introducing an array and using the includes function.

if (['up', 'down', 'left', 'right'].includes(exampleMovement)) {
    // application logic
    // exampleMovement type is string
}
Enter fullscreen mode Exit fullscreen mode

The downside is exampleMovement type is still string.


If we want to narrow the type, we can use a type predicates.

const movementTypeCheck = (movement:string): movement is 'up' | 'down' | 'left' | 'right' => {
    return ['up','down','left','right'].includes(movement);
}

if (movementTypeCheck(exampleMovement)) {
    // application logic
    // exampleMovement type is union of 'up','down','left','right'
}
Enter fullscreen mode Exit fullscreen mode

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay