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

Top comments (0)