我的界面类似于:
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
答案 0 :(得分:2)
您可以在与组件的常用属性相交的交叉点中使用区分联合类型:
type IProps = {
label?: string;
placeholder?: string;
} & ({
withCounter?: false;
maxCounter?: undefined;
} | {
withCounter: true;
maxCounter: number;
})