Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to constrain select's defaultValue to one of the option's values in TypeScript

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" ... />
like image 451
Misha Moroshko Avatar asked Nov 01 '25 09:11

Misha Moroshko


1 Answers

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

like image 168
Titian Cernicova-Dragomir Avatar answered Nov 03 '25 01:11

Titian Cernicova-Dragomir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!