1

There is a type:

type AllKeys = {
  prop1: string
  prop2: string
  prop3: string
}

What I want to achieve is to create another type OneOfKeys that will allow objects to be created with only one of the keys:

const obj: OneOfKeys = { // <-- should work
  prop1: 1
}
const obj: OneOfKeys = { // <-- should work
  prop2: 2
}
const obj: OneOfKeys = { // <-- should not be allowed
  prop1: 1
  prop2: 2
}
const obj: OneOfKeys = { // <-- should not be allowed
  randomProp: 1
}

I tried to create it this way but with this implementation we need to provide all 3 props. I know that we can add ? before : to make them optional, but we won't get an error if more than 1 property is declared on the object. Is there a way to achieve the behavior described?

type OneOfKeys = {
  [Property in keyof AllKeys]: number
}
Dev
  • 355
  • 1
  • 7
  • 24
  • 1
    [This](https://stackoverflow.com/questions/39190154/typescript-restrict-count-of-objects-properties?noredirect=1&lq=1) should answer your question, you can upvote him ;) – Pompedup Nov 22 '22 at 01:44
  • 1
    [This approach](https://tsplay.dev/mArB8W) is how one might do this programmatically; see the linked questions/answers for details. – jcalz Nov 22 '22 at 02:05

0 Answers0