如何将带有另一个字符串枚举的键的枚举传递到接受字符串的函数中?

her*_*tan 9 typescript

我正在尝试将字符串枚举传递到需要字符串的函数中。问题是这个字符串枚举必须从保存我们存储库中所有常量的(全局)常量枚举中分配。

enum Constants {
    hello = "Hello"
}

enum Potato {
    h = Constants.hello
}

function takesAString(s: string) {
    console.log(s + ", world!");
}
takesAString(Potato.h);
// ERROR: Argument of type 'Potato' is not assignable to parameter of type 'string'
Run Code Online (Sandbox Code Playgroud)

虽然人们期望它Potato.h是字符串类型(因为它被分配来自字符串枚举常量的字符串),但实际上它会出错,错误是“Potato”不可分配给字符串类型的参数。这对我来说意味着 Typescript 编译器无法推断 Potato.h 是一个字符串。

有效的事情:

enum Potato {
    h = "Hello"
}

function takesAString(s: string) {
    console.log(s + ", world!");
}
takesAString(Potato.h);
// OK
Run Code Online (Sandbox Code Playgroud)
enum Constants {
    hello = "Hello"
}

enum Potato {
    h = Constants.hello
}

function takesAString(s: string) {
    console.log(s + ", world!");
}
takesAString(Potato.h.toString());
// OK: toString() causes "Hello, world!" to be printed
Run Code Online (Sandbox Code Playgroud)

我正在使用 Typescript 版本 3.8.3

游乐场链接

Tad*_*sen 6

这看起来像是打字稿中的一个错误,我在这里提出了一个错误报告,看起来打字稿将Potato枚举输入为数字,这显然是错误的。

字符串枚举不允许有计算成员,例如,如果您这样做:

declare function returnsString(): string;
enum Test {
    a = returnsString();
} 
Run Code Online (Sandbox Code Playgroud)

你会得到这个错误:

只有数字枚举可以有计算成员,但此表达式的类型为“字符串”。如果不需要详尽检查,请考虑使用对象文字。

因此,您可能想使用对象文字,不需要重写整个代码库,只需将枚举更改为如下所示:

type Constants = typeof Constants[keyof typeof Constants]
const Constants = {
    hello: "Hello"
} as const

type Potato = typeof Potato[keyof typeof Potato]
const Potato = {
    h: Constants.hello
} as const;
Run Code Online (Sandbox Code Playgroud)