Last updated: Feb 27, 2024
Reading timeยท2 min
To check if a string is in a union type:
includes()
method to check if the string is contained in the
array.type Sizes = 'small' | 'medium' | 'large'; function isOfType(value: string): value is Sizes { return ['small', 'medium', 'large'].includes(value); } console.log(isOfType('small')); // ๐๏ธ true console.log(isOfType('medium')); // ๐๏ธ true console.log(isOfType('test')); // ๐๏ธ false
We created a reusable function that takes a string as a parameter and returns
true
if the string is a part of the
union type and false
otherwise.
The
Array.includes()
method returns true
if the supplied value is contained in the array and
false
otherwise.
The value is Sizes
syntax is a
type predicate.
parameter is Type
, where parameter
is the name of a parameter from the function signature.This allows TypeScript to narrow down the variable to a specific type if it is compatible with the original type.
if
statementLet's look at how this works in an if
statement.
type Sizes = 'small' | 'medium' | 'large'; function isOfType(value: string): value is Sizes { return ['small', 'medium', 'large'].includes(value); } const sm = 'small'; if (isOfType(sm)) { // ๐๏ธ const sm: "small" console.log(sm); } else { // ๐๏ธ const sm: never console.log(sm); }
Notice that in the if
block, the sm
variable is correctly typed and it's
typed as never in the else
block.
Had we not used a type predicate, TypeScript would not be able to differentiate
between the type of the variable in the if
and else
blocks.
type Sizes = 'small' | 'medium' | 'large'; // ๐๏ธ removed type predicate function isOfType(value: string) { return ['small', 'medium', 'large'].includes(value); } const sm = 'small'; if (isOfType(sm)) { // ๐๏ธ const sm: "small" console.log(sm); } else { // ๐๏ธ const sm: "small" console.log(sm); }
Now the type of the sm
variable is the same in the if
and else
blocks.
If I add the type predicate back and call the function with a string that is not
in the union, the type of the sm
variable in the if
block will be never
.
type Sizes = 'small' | 'medium' | 'large'; function isOfType(value: string): value is Sizes { return ['small', 'medium', 'large'].includes(value); } const sm = 'TEST'; if (isOfType(sm)) { // ๐๏ธ const sm: never console.log(sm); } else { // ๐๏ธ const sm: "TEST" console.log(sm); }
You can learn more about the related topics by checking out the following tutorials: