【问题标题】:Conditional props in TypeScriptTypeScript 中的条件道具
【发布时间】:2022-01-05 16:54:29
【问题描述】:

我不确定这是否是提出这个条件问题的正确地方,但我们可以在 TypeScript 中做一般类型吗?我经常有如下组件:

type Props = {
  title: string
  buttonLabel?: string
  onButtonClick?: () => void
}

所以我可以选择为按钮提供一个字符串,如果提供了它,那么我还应该提供点击时它会发生什么。但是,如果提供了 buttonLabel,我希望 onButtonClick 是强制性的。一些语法如:

type Props = {
  title: string
  buttonLabel?: string
  onButtonClick<!buttonLabel>: () => void
}

这可以在 Typescript 或任何其他语言中使用吗?

【问题讨论】:

  • 那种。我希望能够在每个道具的基础上定义它,而不必为每个条件类型重复所有类型。虽然这可能是糟糕设计的标志/我可能不知道我在说什么

标签: reactjs typescript types


【解决方案1】:

如果我理解正确的话,你可以通过制作像这样的另一个对象来使 buttonLable 和 onButtonClick 一起成为强制性的:

type Props = {
  title: string
  buttonLink?: string
  buttonData?: {label: string
                onButtonClick: () => void
                }
}

【讨论】:

  • 我想这是一个好方法!很明显,谢谢!
【解决方案2】:

我会将省略两者的类型与需要两者的类型结合起来

type Props = {
  title: string;
} | {
  title: string;
  buttonLabel: string;
  onButtonClick: () => void;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-09
    • 2021-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-09
    • 2021-10-03
    相关资源
    最近更新 更多