Home > Blockchain >  Pass enum as generic to type?
Pass enum as generic to type?

Time:11-04

I have 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>;.

Question: am I able to somehow pass enum as a generic to a type?

CodePudding user response:

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.

CodePudding user response:

If you want to use the Enum keys of A, you need to extract them from the type it self.

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"
}  
}
  • Related