打字稿:通用枚举类型作为另一种类型的索引

发布于 2025-01-31 02:41:51 字数 1082 浏览 4 评论 0原文

我正在尝试创建一种索引类型,其索引是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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

遥远的她 2025-02-07 02:41:51

这个适合您吗?

enum Enum {
  "ABC" = "abc",
  "CDE" = "cde"
}

export type EnumMap<TEnum extends string = Enum> = {
  [key in TEnum]?: string;
}

const map: EnumMap = { [Enum.ABC]: "123" };

由于tenum是字符串联合,因此您可以在索引签名内将其用作[键]

我不确定为什么您使用字符串|未定义的 tenum ...

Does this work for you?

enum Enum {
  "ABC" = "abc",
  "CDE" = "cde"
}

export type EnumMap<TEnum extends string = Enum> = {
  [key in TEnum]?: string;
}

const map: EnumMap = { [Enum.ABC]: "123" };

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 for TEnum...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文