Having only one key of many possible keys in Record in TypeScript

Viewed 53

How can I get autocompletion on the object keys if the keys should be one of the possible strings only?

In the following code, I am getting the required property error. "must" is missing in type '{ must_not: any; }' but required in type 'Operator'.(2741)

type Operator = Record<"must" | "must_not", any>

const x : Operator = {
  must: ...
}

const y : Operator = {
  must_not: ...
}

Where I can have only one of the key names at once either "must" or "must_not".

1 Answers

You can use a distributive conditional type (docs) to create a union of singleton objects, one for each key:

type SingletonUnion<K extends PropertyKey, T> = K extends any ? {[Key in K]: T} : never

(The K extends PropertyKey constraint is to prevent incorrect usage, and the K extends any constraint is to force distribution.)

type Operator = SingletonUnion<"must" | "must_not", any>
// type Operator = { must: any} | {must_not: any}

const x : Operator = {
  must: 'any'
}

const y : Operator = {
  must_not: 'any'
}

TypeScript playground

Related