Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create generic that extends union type of class programaticaly

I have following the code:

const events = {
  a: ['event1' as const, 'event2' as const],
  b: ['event3' as const, 'event4' as const],
};

class SomeClass<
  T extends AnotherClass<typeof events[keyof typeof events][number]>
> {}

T will be: T in SomeClass<T extends AnotherClass<"event1" | "event2" | "event3" | "event4">>

But I would like to see : T in SomeClass<T extends AnotherClass<"event1" | "event2"> | AnotherClass<"event3" | "event4">>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there better way to accomplish this result other that listing all options like this:

class SomeClass<
  T extends
    | AnotherClass<typeof events.a[number]>
    | AnotherClass<typeof events.b[number]>
> {}

>Solution :

We can map over the properties of events:

class SomeClass3<
  T extends {
    [K in keyof typeof events]: AnotherClass<typeof events[K][number]>
  }[keyof typeof events]
> {}

Sandbox

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading