我正在尝试将字符串枚举传递到需要字符串的函数中。问题是这个字符串枚举必须从保存我们存储库中所有常量的(全局)常量枚举中分配。
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
} …Run Code Online (Sandbox Code Playgroud) typescript ×1