Misha Moroshko
Misha Moroshko

Reputation: 171509

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" ... />

Upvotes: 4

Views: 114

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

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 />
}

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

Upvotes: 2

Related Questions