首页 > 解决方案 > 运行时计算的枚举 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

标签: typescriptenums

解决方案


TypeScript 的重点是从 TS 到 JS 的“转换”。枚举通常是与数据类型处于同一级别的强大语言功能,用于强制类型安全。

动态生成枚举是转译器之上的一个级别,是某种元语言,它可以在转译器运行之前使用工具链中的外部工具生成打字稿来实现,但这可能无法与您的编辑器/IDE 很好地集成。整个事情可能与 TypeScript 的目标背道而驰,除非您想完全生成所有内容、转译并且以后不再修改它。


推荐阅读