Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if value exists inside javascript Flow type

I have a Flow type defined as

export type fruit = 'apple' | 'orange' | 'pear';

What I want to do is validate a string and see if it matches any of the values defined in this type.

Is there a way to do this?

like image 941
Dan Pettis Avatar asked Aug 25 '26 08:08

Dan Pettis


1 Answers

The best approach is to use an array then validate by using Array#includes like this.

const fruits = ['apple', 'orange', 'pear'];
const isValid = anyFruit => fruits.includes(anyFruit);

console.log(isValid("apple"));
console.log(isValid("orange"));
console.log(isValid("pear"));
console.log(isValid("banana"));
like image 196
Nguyễn Văn Phong Avatar answered Aug 26 '26 21:08

Nguyễn Văn Phong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!