TS + React:根据 props 有条件地使用接口

问题描述 投票:0回答:1

我正在构建一个组件,它要么应该接收一个名为

text
的道具,要么应该接收子组件 - 不能两者都接收,也不能两者都接收。

✓ 允许

<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没有必需的属性children

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

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

reactjs typescript
1个回答
1
投票

技巧是在有条件的界面键上使用

never

type VariantA = {
    a: string
    b?: never
}

type VariantB = {
    a?: never
    b: number

}

现在您可以同时使用

{ a: 1 }
{ b: "test" }
,但不能同时使用这两个键。

© www.soinside.com 2019 - 2024. All rights reserved.