使用typescript定义一组不兼容的react道具



我用react制作了一个组件MyComponent。我想定义这个组件的道具。

通常我像一样做

type Props = {
foo: string
}
const MyComponent = (props: Props) => ...

以下是我希望始终可用的道具

selected: string <-- required
onSelect(): void <-- required
margin?: string <-- optional

以下是两个不兼容的集合,即只能使用其中一个。

设置一:

compact?: boolean <-- optional
minWidth?: number <-- optional
maxWidth?: number <-- optional

第二套:

width?: number <-- optional

定义这些道具的最佳方式是什么,以便对使用组件的开发人员最有意义?也就是说,什么能提供最好的智能感知体验?

您可以使用never:创建类似XOR的行为

type Props = {
selected: string;
onSelect(): void;
margin?: string;
} & (
| {
compact?: boolean;
minWidth?: number;
maxWidth?: number;
width?: never;
}
| {
compact?: never;
minWidth?: never;
maxWidth?: never;
width?: number;
}
);

然后当你给它无效道具时:

<MyComponent selected="foo" onSelect={() => {}} margin="0" width={0} compact={true} />

你会得到一个相当有用的错误:

类型"{selected:string;onSelect:((=>void;margin:string;width:number;compact:true;}"不可分配给类型"IntrnsicAttributes&道具。类型"{selected:string;onSelect:((=>void;margin:string;width:number;compact:true;}"不可分配给类型"{compact?:未定义;minWidth?:未确定;maxWidth?:未定义;width?:number|undefined;}"。属性"compact"的类型不兼容。类型"true"不可赋值给类型"undefined"。(2322(

游乐场

最新更新