I would like to implement an interface that could be seen like this:
interface SelectProps {
options: Array<{ value: string; text: string }>
currentValue: string
}
But I would like to improve it so the currentValue
property has to be one of the options' value
.
I was thinking of doing something like this:
interface Props<T extends string> {
options: Array<{ value: T; text: string }>
currentValue: T
}
But with that solution I would have to use that interface like this:
const props: Props<'foo' | 'bar' | 'baz'> = {
options: [
{ value: 'foo', text: 'Foo' },
{ value: 'bar', text: 'Bar' },
{ value: 'baz', text: 'Bar' }
],
currentValue: 'foo'
}
But I would like T
to be automatically inferred from options
instead:
const props: Props = {
options: [
{ value: 'foo', text: 'Foo' },
{ value: 'bar', text: 'Bar' },
{ value: 'baz', text: 'Bar' }
],
currentValue: 'zzzz' // Error, no in options
}
How could that be done?
Thanks