typescript - 运行时计算的枚举 TypeScript
问题描述
快速提问,这在 TypeScript 中可行吗?我知道允许使用字符串文字,为什么不允许使用普通字符串?
import * as path from 'path';
enum Path {
Root = path.parse(__dirname).root as Path
}
输出:
application/libs/enums.ts:23:12 - error TS2352: Conversion of type 'string' to type 'Path' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
23 Root = path.parse(__dirname).root as Path
解决方案
TypeScript 的重点是从 TS 到 JS 的“转换”。枚举通常是与数据类型处于同一级别的强大语言功能,用于强制类型安全。
动态生成枚举是转译器之上的一个级别,是某种元语言,它可以在转译器运行之前使用工具链中的外部工具生成打字稿来实现,但这可能无法与您的编辑器/IDE 很好地集成。整个事情可能与 TypeScript 的目标背道而驰,除非您想完全生成所有内容、转译并且以后不再修改它。
推荐阅读
- r - 如何将条件摘要的列和行添加到数据框(总数和百分比)?是否有使用 R 的管道工作流方法?
- android - 如何获取分配给以太网接口的 IP 地址?
- sql - 我想在我的选择查询中使用 totalmon 和 totalcost 而不是 select *
- python - 从 python 脚本调用 .so 两次后崩溃
- javascript - setTimeout 对比 睡眠模式
- chart.js - 在 Chart.js 中更改图例的边框颜色
- javascript - react-bootstrap 表未对齐
- javascript - 将类库 (.net) 的 Javascript 文件链接到 blazor 应用程序
- java - NetBeans 项目在连接到 Tomcat 时卡住
- python - 如何在 Django 中剥离 Prometheus 响应内容?