enums - 如何在 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 中使用字符串值作为文字类型呢?
解决方案
这个呢?
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
推荐阅读
- javascript - 用于比较major.minor.patch 字符串的数组reduce 函数
- javascript - 带有参数的javascript抽象回调
- html - IONIC 4 - 如何在 HTML 中动态添加点击事件
- spring - 具有不同 application.properties 的 Spring Boot 应用程序
- reactjs - 语义 UI 反应
- plsql - SQL%FOUND 对游标结果没有反应
- python - 合并旧作业和新作业#s 的总数
- spring - 带有 POST 请求的 Spring Boot Security CORS
- c# - 在调用 Application.Run() 或实例化 WinForms UserControl 对象时,在 .NET 控制台应用程序中使用 Async/Await 会中断
- android - Android WebView:在 Lineage OS 上使用 firefox/gecko 浏览器引擎