如何将 select 的默认值限制为 TypeScript 中的选项值之一

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

我如何输入 Select 的属性,以便 defaultValue 被限制为 options 值之一(本例中为 "au" | "nz")?

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

您可以使用泛型来捕获 options 道具的类型,您可以使用索引访问类型来获取 value

的实际类型

function Select<T extends { readonly value: string, readonly label: string }>(p: { options: readonly T[], defaultValue: T['value'] }) {
    return <div />
}

Playground Link

您也可以只为 value 字段使用泛型。 (您需要在 defaultValue 上使用 & {} 来降低该推理站点的优先级。


function Select<T extends string>(p: { options: ReadonlyArray<{ value: T, label: string }>, defaultValue: T & {} }) {
    return <div />
}

Playground Link