【发布时间】: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