在 Flow 中使用枚举

如果你曾经接触过一个更传统的面向对象的语言(C、C#、Java),你可能已经看到了一种enum数据类型,虽然JavaScript不支持enums,但Flow的打字检查(https://andsky.com/tech/tutorials/react-flowtype)可以弥补它。

什么地方有用?

假设你正在编写一个处理扑克芯片的程序. 芯片的颜色是一个字符串(即红色,蓝色,等等)。

1type Chip = {
2  color: string,
3};

...并且将创建芯片的函数将是:

1function createChip(color: string): Chip {
2  return {
3    color,
4  };
5}

但你想确保它只使用有效的颜色:

1// This should be valid.
2createChip('red');
3// This should not.
4createChip('cyan');
5// This isn't even a color.
6createChip('Nicomachean Ethics');

创建一个 Enum

最简单的方式来定义一个enum是作为一个连接的字符串:

1// 'red', 'blue', and 'green' are valid colors.
2type Color = 'red' | 'blue' | 'green';

从这里开始,您可以使用类型颜色而不是字符串:

 1type Chip = {
 2  // `color` can only be a valid color.
 3  color: Color,
 4};
 5
 6// `createChip` only takes values of type `Color`.
 7function createChip(color: Color): Chip {
 8  return {
 9    color,
10  };
11}

从现有价值中创建一个Enum

扑克芯片的价值取决于颜色,所以让我们假设你有一个对象,在你的项目中某个地方寻找价值:

1const chipValues = {
2  red: 5,
3  blue: 10,
4  green: 25,
5};

颜色类型重复了chipValues的密钥,当只有三个密钥时,它并不那么糟糕,但它仍然是重复,如果添加更多密钥,它会变得令人烦恼。

1type Color = $Keys<typeof chipValues>;
Published At
Categories with 技术
Tagged with
comments powered by Disqus