How to define a function with an object with multiple entries as an argument, that only accepts one entry?

Viewed 43

Imagine a function that get an object as argument that has two entries with any possible type.

const x = ({a,b}:{a: string, b: string}) => {
    // return something
}

x({a: "foo"}) // OK
x({b: "bar"}) // OK
x({a: "foo", b: "bar"}) // get a compile error in this case!

How can we set this function in a way that only one of the entries be passed to function? In other words, I need to get a compile error when both entries are set inside the function? For example, if "a" is already passed, the moment "b" is also passed we get a compilation error and vice versa.

1 Answers

My original intuitive, and obviously wrong, answer: Use a union type:

{ a: string } | { b: string }

This will not trigger a compile error for x({a: "foo", b: "bar"}).

Working solution: You can follow this advice for “mutually exclusive types”:

type Without<T, U> = { [P in Exclude<keyof T, keyof U>]?: never };
type XOR<T, U> = (T | U) extends object ? (Without<T, U> & U) | (Without<U, T> & T) : T | U;

const x = (args: XOR<{ a: string }, { b: string }>) => {
    // return something
}

x({a: "foo"}) // OK
x({b: "bar"}) // OK
x({a: "foo", b: "bar"}) // get a compile error in this case!

See TypeScript Playground

Related