【问题标题】:How to constrain select's defaultValue to one of the option's values in TypeScript如何将选择的 defaultValue 限制为 TypeScript 中的选项值之一
【发布时间】:2021-11-12 19:26:41
【问题描述】:

我如何键入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" ... />

【问题讨论】:

  • 如果你知道你的countryOptions 总是包含多个值,你能像&lt;Select options={countryOptions} defaultValue={countryOptions[0].value} ... /&gt; 那样做吗?
  • 你使用的是哪个库?

标签: reactjs typescript html-select


【解决方案1】:

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


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

Playground Link

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


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

Playground Link

【讨论】:

  • 谢谢!!我在哪里可以了解有关&amp; {} 位的更多信息?
  • @MishaMoroshko ?‍♂️ 我不久前在 github 问题上发现了它。不太确定它是否在其他地方明确记录
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-04
  • 2019-01-18
  • 2019-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-16
相关资源
最近更新 更多