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.
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">;
// −−−−−−−−−−−−−−−^^^^^^^
}