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" ... />
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 />
}
Playground Link
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 />
}
Playground Link
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With