【发布时间】:2017-07-19 19:32:32
【问题描述】:
【问题讨论】:
-
请粘贴代码而不是代码的图像。它可以帮助那些试图帮助你的人。
-
感谢您提供的链接包含适合我的案例的最佳解决方案
标签: typescript enums
【问题讨论】:
标签: typescript enums
对于任何enum,请使用any。
function getText(enumValue: number, typeEnum: any): string;
要限制可能的枚举,请使用联合类型。
function getText(enumValue: number, typeEnum: typeof Car | typeof Color): string;
【讨论】:
function getText<E>(enumValue: number, typeEnum: E): string;
我认为没有一种简单的方法可以像您想要的那样说“仅支持枚举”。不过,您有一些选择。你可以继续添加你想要支持的枚举:
enum Color {};
enum Car {};
type SupportedEnums = typeof Color | typeof Car;
function getText(enumValue: number, typeEnum: SupportedEnums) {
retrun `${enumValue}(${typeEnum[enumValue]})`;
}
或者,不用维护SupportedEnums,直接使用any类型。
====
原答案:
您可以使用typeof引用类型:
getText(enumValue: number, typeEnum: typeof Color): string {
return typeEnum[enumValue];
}
【讨论】:
TS2693: 'Color' only refers to a type, but is being used as a value here.