0

Is it possible to do the following in Typescript:

I have an object whose keys are properties and values are an array of the options for these properties:

const options = {
  foo: [fooOption1, fooOption2, ...],
  bar: [barOption1, barOption2, ...],
  ...
}

Is it possible to create an interface such that

interface example {
  foo: fooOption1 | fooOption2 | ...,
  bar: barOption1 | barOption2 | ...,
  ...
}
arcrub
  • 170
  • 1
  • 11

1 Answers1

1

Firstly, change your options object to a constant:

const options = {
  foo: ['fooOption1', 'fooOption2'],
  bar: ['barOption1', 'barOption2']
} as const;

Then, you can create desired interface by mapping each array to an union:

type OptionsInterface = {
    [K in keyof typeof options]: typeof options[K][number]
}


const xx: OptionsInterface = {
   foo: 'fooOption1',
   bar: 'barOptionError' // Expected error: 
                         // Type '"barOptionError"' is not assignable to type '"barOption1" | "barOption2"'.(2322)
}

See:

Lesiak
  • 22,088
  • 2
  • 41
  • 65
  • Thanks a lot, that's very helpful! I thought you couldn't do this, but it seems it's only not possible for interfaces. – arcrub Feb 22 '21 at 11:15