如何检查JavaScript Flow类型中的值是否存在

3

我有一个定义如下的Flow类型

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

我想要做的是验证一个字符串,看它是否与此类型中定义的任何值匹配。有没有方法可以做到这一点?
3个回答

1
最好的方法是使用一个数组,然后使用Array#includes进行验证,就像这样。

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"));


这个回答解决了你的问题吗?如果需要任何帮助,请告诉我 ^^!@Dan Pettis - Nguyễn Văn Phong

0

这肯定有点笨重,但你也可以这样做:

type FruitMap = {
  apple: '',
  pear: '',
}

const FRUIT_MAP: FruitMap = Object.freeze({
  apple: '',
  pear: '',
});

type Fruit = $Keys<FruitMap>;

const apple = 'apple';
const isFruit = Object.keys(FRUIT_MAP).includes(apple);

0

如果你想从字符串中将类型细化为其中一个值,目前还没有一种优雅的方法来实现这个功能。

几天前这里发布了一个非常相似的问题 here,还有一个问题提出here
为了以流畅的方式完成此操作并避免出现错误,您需要手动使用 if 语句或 switch 语句输入组合。

尝试一下

// @flow
type fruit = 'apple' | 'orange' | 'pear';

const func = (f: string): fruit | void => {
  const fruits = ['apple', 'orange', 'pear'];
  if (fruits.includes(f)) {
    return f; // This one errors out because you cannot type refine using
  }
}

const func2 = (f: string): fruit | void => {
  if (f === 'apple' || f === 'orange' || f === 'pear') {
    return f;
  }
}

const func3 = (f: string): fruit | void => {
  switch (f) {
    case 'apple':
    case 'orange':
    case 'pear':
      return f;
  }
}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接