reactjs - TS + React:根据 props 有条件地使用接口
我正在构建一个组件,该组件应该接收一个名为 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 来说它可以工作,但在仅使用 text 属性时,React 会给出警告:
<NotificationBar text="Demo"/>
元素 NotificationBar 缺少必需的属性 children
除此之外,它的运行符合预期。
我还能如何为我的 React 组件创建一个接口,使其匹配基于给定 props 的接口,并且不出现警告?
答案#1
诀窍是在条件性的接口键上使用 never。
type VariantA = {
a: string
b?: never
}
type VariantB = {
a?: never
b: number
}
现在你可以有 { a: 1 } 或 { b: "test" },但不能同时有两个键。
