Typescript。如果传递了属性1,则需要属性2

问题描述 投票:0回答:1

我有类似的界面:

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
typescript typescript2.0
1个回答
0
投票

您可以在与组件的公共属性相交的位置使用判别联合类型:

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

Playground Link

© www.soinside.com 2019 - 2024. All rights reserved.