maninak / ts-xor

Compose object types containing mutually exclusive keys, using this generic Typescript utility type.
https://app.radicle.at/nodes/seed.radicle.at/rad:z3nP4yT1PE3m1PxLEzr173sZtJVnT
MIT License
106 stars 5 forks source link

XOR based on keys #29

Open Birkbjo opened 1 year ago

Birkbjo commented 1 year ago

Hello, thanks for this utility type. However, my usecase is usually to create a type of an object where only certain keys of that same object are mutually exclusive. I wonder if there's any interested to include a type for this? I know it's quite easily possible by creating new types of the object (using omit for instance), but an "API" like this would be a bit easier:

type MutuallyExclusive<T, U extends keyof T> = ...

type BaseButtonProps = {
    primary?: boolean
    destructive?: boolean
    secondary?: boolean
    type: string
}

type ButtonProps = MutuallyExclusive<BaseButtonProps, 'primary' | 'secondary' | 'destructive'>

I created a helper type for this. I've done limited testing, but it seems to work for my use case at least. Would this be something that would be useful to include in this repo?

type MutuallyExlusive<T extends object, U extends keyof T> = Prettify<
    T &
        {
            [K in U]: WithoutObj<Pick<T, U>, Pick<T,K>> & T
        }[U]
>
Birkbjo commented 1 year ago

Closing, because I found some bugs in my implementation. Might reopen if I manage to solve them

Edit: I managed to simplify the utility type, which seems to have fixed the issues I faced.