首页 > 解决方案 > 如何在 Flowtype 中使用字符串值作为文字类型?

问题描述

打字稿允许我有这样的定义:

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 中使用字符串值作为文字类型呢?

标签: enumsflowtype

解决方案


这个呢?

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

推荐阅读