Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TypeScript provide alternative types while using keyof

I want to have a type that when specifying a specific key as the value to the property answerMethod (e.g. answerMethod: 'options') it should require an additional field (e.g. a string array with options)

Here is a non-working attempt at what I’ve been wanting to achieve:

const formComponents = {
  text: TextInput,
  options: Radio,
}

interface AnswerBase {
  name: string
  label: string
  helpText?: string
  value?: string
}

interface AnswerWithoutOptions extends AnswerBase {
  answerMethod: Omit<keyof typeof formComponents, 'options'>
}

interface AnswerWithOptions extends AnswerBase {
  answerMethod: 'options'
  options: string[]
}

type Answer = AnswerWithoutOptions | AnswerWithOptions

const answer: Answer = {
  name: 'title',
  label: 'Title',
  helpText: 'The title of the video.',
  answerMethod: 'notavalidmethod', // Expected an error.
  value: '',
}

The above code only allows the field options: string[] when answerMethod: 'options', but it doesn’t restrict answerMethod to be a key of formComponents and allows any string. answerMethod should only allow keys of formComponents.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Any guidance would be appreciated.

>Solution :

You want Exclude, not Omit. Omit is for removing keys from a type. It’s Exclude that excludes members from a union.

interface AnswerWithoutOptions extends AnswerBase {
    answerMethod: Exclude<keyof typeof formComponents, "options">;
// −−−−−−−−−−−−−−−^^^^^^^
}

Playground link

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading