我有类似的界面:
interface IProps {
label?: string;
placeholder?: string;
withCounter?: boolean;
maxCounter?: number;
}
如何告诉打字稿,如果有人通过withCounter也需要将maxCounter传递给我的React组件。
示例我想实现的目标:
<CustomComponent label="example" /> // OK
<CustomComponent label="example" withCounter={true} /> // ERROR no property maxCounter
<CustomComponent label="example" withCounter={true} maxCounter={100}/> // OK
<CustomComponent label="example" maxCounter={100}/> // ERROR no property withCounter
您可以在与组件的公共属性相交的位置使用判别联合类型:
type IProps = {
label?: string;
placeholder?: string;
} & ({
withCounter?: false;
maxCounter?: undefined;
} | {
withCounter: true;
maxCounter: number;
})