【问题标题】:TS + React: Conditionally use interface based on propsTS + React:有条件地使用基于 props 的接口
【发布时间】:2019-05-24 11:27:13
【问题描述】:

我正在构建一个组件,它要么应该接收一个名为 text 的 prop,要么接收孩子 - 既不是两者也不是。

✓ 允许

<NotificationBar text="Demo"/>
<NotificationBar>Demo</NotificationBar>

✗ 不允许

<NotificationBar/>
<NotificationBar text="Demo">Demo</NotificationBar>

来源

interface IWithChildren {
    children: ReactNode;
    text?: never;
}

interface IWithText {
    text: JSX.Element | string;
    children?: never;
}

type TNotification = (IWithChildren | IWithText);

export const NotificationBar = ({ text, children }: TNotification) => {}

TypeScript 方面它可以工作,但 React 仅在使用 text 属性时会发出警告:

<NotificationBar text="Demo"/>

元素 NotificationBar 没有必需的子属性

除此之外,它按预期工作。

我怎样才能为我的 React 组件创建一个接口,它根据给定的 props 匹配一个接口,并且不会收到警告?

【问题讨论】:

  • 你可以在这里复制这个codesandbox.io/s/react-ts 吗?
  • 您收到的警告是由您的 IDE 发出的?因为我只是尝试复制/粘贴您写的内容,VSCode 没有给出警告
  • 我理解你的想法,但也许你应该考虑只使用儿童道具。这个 API 设计有点混乱 imo。我认为在这种情况下使用儿童道具是全球标准,而不是从我的脑海中浮现。

标签: reactjs typescript


【解决方案1】:

诀窍是在有条件的界面键上使用never

https://codesandbox.io/s/admiring-almeida-o4wxj

【讨论】:

  • 这个链接失效了:(
猜你喜欢
  • 1970-01-01
  • 2020-11-04
  • 2021-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-05
  • 1970-01-01
  • 2021-08-10
相关资源
最近更新 更多