Ogen
Ogen

Reputation: 6709

Type that only allows values from an enum but does not require every value in the enum to be present

I have the following code:

enum Foo {
  a,
  b,
  c
}

type Bar = {
  [key in keyof typeof Foo]: string;
}

const test: Bar = {
  a: 'a',
  b: 'b'
};

The code complains that the test variable does not have the c property.

How can I alter the Bar type so that the keys from the enum are optional?

Upvotes: 0

Views: 49

Answers (2)

Maciej Sikora
Maciej Sikora

Reputation: 20132

The simplest solution by utility types Partial and Record

type Bar = Partial<Record<keyof typeof Foo, string>>

Upvotes: 0

Robby Cornelissen
Robby Cornelissen

Reputation: 97140

You could use a Partial<T>:

enum Foo {
  a,
  b,
  c
}

type Bar = Partial<{
  [key in keyof typeof Foo]: string;
}>

const test: Bar = {
  a: 'a',
  b: 'b'
};

Or, as mentioned in the comments by @jcalz, mark the properties as optional:

enum Foo {
  a,
  b,
  c
}

type Bar = {
  [key in keyof typeof Foo]?: string;
}

const test: Bar = {
  a: 'a',
  b: 'b'
};

Upvotes: 1

Related Questions