打字稿:通用枚举类型作为另一种类型的索引
我正在尝试创建一种索引类型,其索引是enum
的值,但enum
来自通用参数。
export type EnumMap<TEnum extends string | undefined = undefined> = {
[key: TEnum]: ValueClass;
}
export type EnumMap<TEnum extends string | undefined = undefined> = {
[key: keyof TEnum]: ValueClass;
}
这两个实现都显示出错误:
索引签名参数类型不能是字面类型或通用类型。考虑使用映射的对象类型。
当我按建议的对象实现它时:
export type EnumMap<TEnum extends string | undefined = undefined> = {
[TEnumKey in keyof TEnum]: ValueClass;
}
它在定义上没有显示任何错误,但仅接受tenum
实例作为值。当我尝试实例化enummap
时,它显示了此错误。
类型'{“ test”:valueclass; }'不能分配给'testEnum'。
我正在使用此enum
作为测试:
export enum TestEnum {
test = 'test'
}
是否有任何方法可以使用通用enum
作为类型的索引?
ps。:我知道我可以使用字符串作为密钥来实现它,但是我想将索引与枚举值联系起来;
export type EnumMap = {
[key: string]: ValueClass;
}
const map: EnumMap = { [TestEnum.test]: {...} }; // works fine
I'm trying to create an indexed type whose index are the values of an enum
BUT the enum
comes from a generic argument.
export type EnumMap<TEnum extends string | undefined = undefined> = {
[key: TEnum]: ValueClass;
}
export type EnumMap<TEnum extends string | undefined = undefined> = {
[key: keyof TEnum]: ValueClass;
}
Both of those implementations shows the error:
An index signature parameter type cannot be a literal type or generic type. Consider using a mapped object type instead.
When I implement it as a mapped object as suggested:
export type EnumMap<TEnum extends string | undefined = undefined> = {
[TEnumKey in keyof TEnum]: ValueClass;
}
It doesn't show any errors at the definition but it only accepts TEnum
instances as the value. It shows this error when I try to instantiate an EnumMap
.
Type '{ "test": ValueClass; }' is not assignable to type 'TestEnum'.
I'm using this enum
as a test:
export enum TestEnum {
test = 'test'
}
Is there any way to use a generic enum
as a type's index?
PS.: I understand I can implement it using string as the key, but I want to tie the indexes to the enum values;
export type EnumMap = {
[key: string]: ValueClass;
}
const map: EnumMap = { [TestEnum.test]: {...} }; // works fine
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这个适合您吗?
由于
tenum
是字符串联合,因此您可以在索引签名内将其用作[键]
。我不确定为什么您使用
字符串|未定义的
tenum
...Does this work for you?
Since
TEnum
is a string union, you can use it as[key in TEnum]
inside the index signature.I am not sure why you used
string | undefined
forTEnum
...