Skip to content

How to implement n-ary Extract? #23413

Closed
Closed

Description

I built a tiny library that makes mixins typesafe, including detecting method collisions at compile time. The implementation is really simple, and it's a nicer API than the one in the TS handbook, I think.

I'm having trouble extending it to support more than a few parameters passed to mixin(A, B, C), because I have to test all permutations for Extract to work:

  • 2-ary mixin():
    • Extract<keyof A, keyof B>
  • 3-ary mixin():
    • Extract<keyof A, keyof B | keyof C>
    • Extract<keyof A | keyof C, keyof B>
  • 4-ary mixin():
    • Extract<keyof A, keyof B | keyof C | keyof D>
    • Extract<keyof A | keyof D, keyof B | keyof C>
    • Extract<keyof A | keyof C, keyof B | keyof D>
    • Extract<keyof A | keyof C | keyof D, keyof B | keyof D>

This quickly explodes and gets really branchy, making the PreventCollisions type (below) really unwieldy.

Any suggestions for how to avoid this branchieness, to support more params? The thing I'd like to express is "What are the keys that shapes A, B, C ... Z have in common?"

The issue tracker is not the best place for questions like these, but I thought TS maintainers would be interested to see this solution. Feel free to close if you feel otherwise :)

Code is here: https://github.com/bcherny/magical-mixin/blob/master/src/index.ts.

Relevant section is:

type PreventCollisions<A, B, C = never> = Extract<keyof A, keyof B | keyof C> extends never
  ? Extract<keyof A | keyof C, keyof B> extends never
    ? Ctor<A & B & C>
    : 'Error' & Methods<Extract<keyof A | keyof C, keyof B>>
  : 'Error' & Methods<Extract<keyof A, keyof B | keyof C>>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions