一个道具的类型取决于另一个道具的类型

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

是否有可能以某种方式结合下面两种类型的 React 组件道具的描述。

isEdit == true

type DialogProps = {
  isEdit: boolean
  obj: ICustom
}

isEdit == false

type DialogProps = {
  isEdit: boolean
  obj: null
}
typescript react-props
1个回答
0
投票

您可以尝试将 DialogProps.obj 设为通用类型

type DialogProps<T> = {
  isEdit: boolean;
  obj: T extends true ? ICustom : null;
};

// Usage:
const editProps: DialogProps<true> = {
  isEdit: true,
  obj: { /* ICustom properties */ },
};


根据T的值判断obj prop类型的条件类型。当T为真时,obj的类型为ICustom,当T为假时,这样,你可以为两种情况重用相同的DialogProps类型,并且仍然保持类型安全。

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