我试图将字符串枚举传递给需要字符串的函数。问题是必须从(全局)常量枚举中分配此字符串枚举,该枚举包含我们存储库中的所有常量。
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
是字符串类型的(因为它是从字符串枚举常量中分配了一个字符串),但实际上它会出错,并且错误是“土豆”无法分配给字符串类型的参数。在我看来,这意味着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
这看起来像是打字稿中的错误,我在这里提出了一个错误报告看起来打字稿正在将Potato
枚举键入为数字,这显然是错误的。
字符串枚举不允许具有计算成员,例如,如果您这样做:
declare function returnsString(): string;
enum Test {
a = returnsString();
}
您收到此错误:
只有数字枚举可以具有计算成员,但是此表达式的类型为“字符串”。如果不需要穷举检查,请考虑改用对象文字。
因此,您可能想使用对象文字,它不需要重写整个代码库,只需将枚举更改为以下形式即可:
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;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句