1

I want to create a type MaxOneProp where you should only be allowed to specify exactly one property. Possible property names are listed in the Props type.

type Props = 'a' | 'b' | 'c'

type MaxOneProp = Partial<{ [K in Props]: string }>

// should be valid

const a: MaxOneProp = {
  a: "abc"
}


// should not be valid

const b: MaxOneProp = {}

const c: MaxOneProp = {
  b: "abc",
  c: "abc"
}

My current approach Partial<{ [K in Props]: string }> does not in any way limit the amount of properties of the object.

Playground

Tobias S.
  • 21,159
  • 4
  • 27
  • 45
  • 1
    Does this answer your question? [How to create a Partial-like that requires a single property to be set](https://stackoverflow.com/questions/48230773/how-to-create-a-partial-like-that-requires-a-single-property-to-be-set) – Daniel Rodríguez Meza Apr 18 '22 at 18:41
  • this is asking for "exactly" and not "at least", so the other question doesn't quite apply here – jcalz Apr 18 '22 at 19:11
  • Does [this approach](https://tsplay.dev/w8oYMW) meet your needs? If not, what am I missing? – jcalz Apr 18 '22 at 19:14
  • Your title implies "zero or one" while your question talks about "exactly one". I wouldn't say `MaxOne` and I wouldn't say "not more than one". Could you [edit] the question to be clear here? – jcalz Apr 18 '22 at 19:16
  • @jcalz thanks, it works perfectly. Do you have a link to the documentation which explains what the assignment in `K extends keyof T = keyof T` does exactly? – Tobias S. Apr 18 '22 at 20:16
  • 1
    It's a [generic default](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-3.html#generic-parameter-defaults) and in this case it's being used to get `keyof T` assigned to a generic type parameter `K` so we can then break it up into its union constituents via a [distributive conditional type](https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types). – jcalz Apr 18 '22 at 20:23

0 Answers0