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
}
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
}
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'
}
Top comments (0)