Home > database >  How to create generic that extends union type of class programaticaly
How to create generic that extends union type of class programaticaly

Time:04-30

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

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]>
> {}

CodePudding user response:

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

  • Related