underfrankenwood
underfrankenwood

Reputation: 893

Pass enum as generic to type?

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?

Upvotes: 1

Views: 1647

Answers (2)

Pedro Figueiredo
Pedro Figueiredo

Reputation: 2452

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

Upvotes: 0

raina77ow
raina77ow

Reputation: 106385

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.

Upvotes: 2

Related Questions