简体   繁体   English

将枚举作为泛型传递给类型?

[英]Pass enum as generic to type?

I have enum :我有enum

enum A {
  a = 'a',
  b = 'b',
}

And a type:还有一个类型:

type B<T = A> = {
   values: Record<T, string>; // error Type 'T' does not satisfy 
           //              the constraint 'string | number | symbol'.   

   // Type 'T' is not assignable to type 'symbol'.
}

Then I want to use it const someVar: B<someEnum>;然后我想用它const someVar: B<someEnum>; . .

Question: am I able to somehow pass enum as a generic to a type ?问题:我能否以某种方式将enum作为泛型传递给type

Yes, if you're ok with something like this:是的,如果你对这样的事情没意见:

type B<T extends A = A> = {
   values: Record<T, string>;
}

You won't be able to generalize enum though.但是,您将无法概括枚举。 Quoting the docs :引用文档

In addition to generic interfaces, we can also create generic classes.除了泛型接口,我们还可以创建泛型类。 Note that it is not possible to create generic enums and namespaces.请注意,无法创建通用枚举和命名空间。

If you want to use the Enum keys of A , you need to extract them from the type it self.如果要使用A的 Enum 键,则需要从它自己的类型中提取它们。

Here is a sample on how you can achieve that:以下是有关如何实现这一目标的示例:

enum A {
  a = 'a',
  b = 'b',
}

type B<T extends string = keyof typeof A> = {
   values: Record<T, string>;
  }

const object1 : B = {
values: {
  "a": "123",
  "b": "123"
}  
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM