0

I need a type in which some optional properties depend on each other.
I.e. if an object defines one such property, then it must define all other properties that depend on it.

I thought of separating the main type and the sets of optional properties, and then having a union type, but it doesn't seem to work.
Namely, I expect that if

interface T {a: any, b: any}
interface U {c: any, d, any}
type V = T | (T & U)

Then v: V would only be able to contain either {a, b} or {a, b, c, d}.
However, typescript shows no error when v only has {a, b, c} (which is neither T, nor T & U).
What am I missing?
Also, could there be a more succint way of expressing T | (T & U)?

  • `{a, b, c}` is indeed `T`; TypeScript has [structural subtyping](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html#structural-type-system). – jcalz Sep 24 '21 at 14:37
  • Welcome to Stack Overflow! Please make sure that your example code does not contain any typographical errors. – jcalz Sep 24 '21 at 14:38
  • @jcalz It would be interesting why excess property checking doesn't apply in this case, though, with `const v1: V = {a: 1, b: 1, c: 1}`. – Ingo Bürk Sep 24 '21 at 14:40
  • Does [this code](https://tsplay.dev/w11O2w) meet your needs? Please note that the "more succinct" part of the question is not addressed and [probably should be a separate question](https://meta.stackexchange.com/questions/222735/can-i-ask-only-one-question-per-post) – jcalz Sep 24 '21 at 14:42
  • 1
    @IngoBürk that's [this issue](https://stackoverflow.com/questions/46370222/why-does-a-b-allow-a-combination-of-both-and-how-can-i-prevent-it) – jcalz Sep 24 '21 at 14:44
  • @jcalz Thanks, it works! Looks like I got confused the adherence to a type with excess property checking. And the latter doesn't currently work with union types as I expected. – Yoba Yoba Sep 24 '21 at 15:01
  • So, do you think you need a specific answer to this, or does the answer to [this question](https://stackoverflow.com/q/46370222/2887218) suffice? It's very similar, since you want to "exclusify" the `T | (T & U)` union to make `V`... if I translate that code here it gives [this](https://tsplay.dev/WJ8OZN). I'm inclined to close this as a duplicate of that, unless you think something is missing from that answer. – jcalz Sep 24 '21 at 18:36
  • The solution you've provided is good enough for me, and I agree with closing this as a duplicate. Thanks for help. – Yoba Yoba Sep 25 '21 at 17:36

0 Answers0