我正在尝试将字符串枚举传递给需要字符串的函数。不足之处在于,必须从一个(全局)常量枚举中分配此字符串枚举,该枚举包含我们存储库中的所有常量。
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'
尽管人们期望Potato.h
是字符串类型的(因为它是从字符串枚举常量中分配了一个字符串),但实际上它会出错,并且错误是无法将'Potato'分配给参数字符串类型。在我看来,这意味着Typescript编译器无法推断Potato.h是字符串。
有效的方法:
enum Potato {
h = "Hello"
}
function takesAString(s: string) {
console.log(s + ", world!");
}
takesAString(Potato.h);
// OK
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
我正在使用Typescript版本3.8.3
答案 0 :(得分:1)
这看起来像是打字稿中的错误,我提出了一个bug report here,看起来打字稿正在将Potato
枚举键入为数字,这显然是错误的。
字符串枚举不允许具有计算成员,例如,如果您这样做:
declare function returnsString(): string;
enum Test {
a = returnsString();
}
您收到此错误:
只有数字枚举可以具有计算成员,但是此表达式的类型为'string'。如果不需要穷举检查,请考虑改用对象文字。
因此,您可能要使用对象文字,它不需要重写整个代码库,只需将枚举更改为以下内容即可:
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;