如何在Flowtype中将字符串值用作文字类型?

时间:2019-06-20 14:40:56

标签: enums flowtype

Typescript使我可以定义如下:

export enum LineType {
  Adventure,
  Lift
}

export type AdventureLine =
{
  type: LineType.Adventure;
}

我可以在Flow中做类似的事情:

export const LineType = {
  Adventure: "Adventure",
  Lift: "Lift"
}
Object.freeze(LineType);
export type LineTypeEnum = $Enum<typeof LineType>;

export type AdventureLine =
{
  type: LineType.Adventure;
}

但这不能编译type: LineType.Adventure;-Flow说:“不能将字符串用作类型”。当然可以写type: "Adventure";,但这不是很干。

那么如何在Flow中将字符串值用作文字类型?

3 个答案:

答案 0 :(得分:1)

这样对您有用吗?

type LineType = { Adventure: "Adventure", Lift: "Lift" };
type AdventureLine = { type: $PropertyType<LineType, 'Adventure'> };

({ type: "Adventure" }: AdventureLine); // no error
({ type: "Lift" }: AdventureLine); // error

Try Flow

答案 1 :(得分:1)

this呢?

const Adventure: "Adventure" = "Adventure";
const Lift: "Lift" = "Lift";

export const LineType = {  Adventure,  Lift };
Object.freeze(LineType);
export type LineTypeEnum = $Enum<typeof LineType>;

export type AdventureLine =
{
  type: typeof LineType.Adventure;
}

({ type: "Adventure" }: AdventureLine); // works

({ type: "x" }: AdventureLine); // gives erros

答案 2 :(得分:0)

(我知道这是一个老问题,但是它出现在搜索结果中,所以我想正确地回答如何使用现代Flow来解决这个问题。)

我认为,完成所需操作的方法是使用$Keys<T>实用程序运算符。

https://flow.org/en/docs/types/utilities/#toc-keys

// @flow
const LineTypes = {
  Adventure: "Adventure",
  Lift: "Lift",
}

type LineType = $Keys<typeof LineTypes>

const geometryType = LineTypes.Adventure
const AdventureLine: LineType = 'Adventure'

// $ExpectError
const wontWork: LineType = 'Foo'

Try Flow

也要说明一下Flow与Typescript的Enum不完全相同的原因,这是因为Flow非常小心地只是一个类型系统,而Typescript是一种语言,因此它可以使用Enum之类扩展常规Javascript。因此,根本原因是:Javascript没有枚举,所以Flow没有枚举。一旦Javascript本身具有Enum,Flow也将支持它。

相关问题