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 | ...,
  ...
}

1 Answer 1

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:

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, that's very helpful! I thought you couldn't do this, but it seems it's only not possible for interfaces.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.