Reputation: 171509
How could I type Select
's props so that the defaultValue
is constrained to one of the options
values ("au" | "nz"
in this example)?
const countryOptions = [
{
value: "au",
label: "Australia",
},
{
value: "nz",
label: "New Zealand",
}
] as const;
// This should produce an error because "foo" is neither "au" or "nz"
<Select options={countryOptions} defaultValue="foo" ... />
Upvotes: 4
Views: 114
Reputation: 250416
You can use generics to capture the type of the options
props and you can use indexed access types to get the actual type of value
function Select<T extends { readonly value: string, readonly label: string }>(p: { options: readonly T[], defaultValue: T['value'] }) {
return <div />
}
You could also use a generic just for the value
field. (You will need to use & {}
on defaultValue
to decrease the priority of that inference site.
function Select<T extends string>(p: { options: ReadonlyArray<{ value: T, label: string }>, defaultValue: T & {} }) {
return <div />
}
Upvotes: 2