1

Can I somehow fix this code so that typescript prevents a and b from being used together?

type A = {
  a: number;
}

type B = {
  b: number;
}

type C = {
  c: number;
}

type D = (A | B) & C;

const d0: D = { a: 123, c: 123 } // OK
const d1: D = { b: 123, c: 123 } // OK
const d2: D = { a: 123, b: 123, c: 123 } // NOT OK
Just Alex
  • 183
  • 1
  • 12
  • 1
    See [the answer](https://stackoverflow.com/a/46370791/2887218) to the question this duplicates for more information. If I translate the code in that answer to this example it gives [this result](https://tsplay.dev/WPj95N). Good luck! – jcalz Jul 30 '21 at 15:26
  • This package also makes life easy: https://www.npmjs.com/package/ts-xor With it, you can say `type D = XOR & C;` – funkizer Jul 30 '21 at 15:29
  • I saw `XOR` in `ts-essentials` package, but it works only with 2 objects: https://github.com/krzkaczor/ts-essentials/issues/183 The solution from @jcalz works very well. I used it. – Just Alex Jul 30 '21 at 22:21

0 Answers0