【发布时间】:2021-11-08 14:49:54
【问题描述】:
我使用几个枚举作为全局参数。
enum color {
'red' = 'red',
'green' = 'green',
'blue' = 'blue',
};
enum coverage {
'none' = 'none',
'text' = 'text',
'background' = 'background',
};
我将所有枚举合并到一个类型myEnums。
type myEnums = color | coverage;
现在我想检查和访问枚举的值。例如:
// Returns undefined if the argument value is not a color.
function getColor(value: string): color | undefined{
if(value in color) return value as color;
return undefined;
}
因为有几个枚举,我想创建一个通用函数来访问我的所有枚举。我尝试了以下方法:
function getParam<T extends myEnums>(value: string): T | undefined {
if(value in T) return value as T;
return undefined;
}
getParam<color>('red', color); // => should return 'red'
getParam<coverage>('test', coverage); // => should return undefined
但是 Typescript 编译器说: 'T' 仅指一种类型,但在这里用作值。'。
所以我在函数中添加了一个参数 list: T,但 Typescript 假定参数 list 的类型为 string(而不是 object)。
'in' 表达式的右侧不能是原语。
function getParam<T extends allEnums>(value: string, list: T): T | undefined {
if(value in list) return value as T;
return undefined;
}
那么如何使用T 作为枚举来调用泛型函数?
【问题讨论】:
标签: typescript typescript-generics