打字稿。如果传递了属性1,则需要属性2

时间:2019-12-11 10:45:42

标签: typescript typescript2.0

我的界面类似于:

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

1 个答案:

答案 0 :(得分:2)

您可以在与组件的常用属性相交的交叉点中使用区分联合类型:

type IProps = {
  label?: string;
  placeholder?: string;
} & ({
  withCounter?: false;
  maxCounter?: undefined;
} | {
  withCounter: true;
  maxCounter: number;
})

Playground Link