繁体   English   中英

带有接口的打字稿中的条件布尔类型

[英]Conditional boolean type in typescript with interface

我将如何为此编写条件布尔类型?

IE

export interface Props {
  editable: boolean;
  position: { editable: true } ? Sheets.Matrix : never;
  value: string;
  classNames?: string;
  textType?: "bold" | "editing" | "normal";
  onChange?: (val: Sheets.SaveData) => void;
}

我用这样的道具

const SheetsCell: React.FC<MainProps> = ({
  editable,
  value,
  textType = "normal",
  classNames = "",
  position,
  ...

在这里,如果某些内容是可编辑的,我希望位置类型为Sheets.Matrix否则,不需要位置。

一种方法是使用接口和交集运算符 ( & )。

您可以使用intersection type ,它将多种类型组合为一种。

interface Props {
  value: string;
  classNames?: string;
  textType?: "bold" | "editing" | "normal";
  onChange?: (val: number) => void;
}

type MainProps = Props & {
  editable: true;
  position: number; 
} | Props & {
  editable: false;
  position?: number; 
}; 

上面的MainProps类型强制editable在一种情况下为true ,在另一种情况下为false 如果editabletrue ,则存在 position 属性;如果为false,则存在 position 属性但不是必需的。

上面使用unions来生成可以是两个值之一的类型。 MainProps可以是两种类型之一(都是与Props类型的交集)。

这是游乐场链接

您可以使用类型别名而不是接口,例如

type Props = { 
  editable: true;
  position: Sheets.Matrix;
} | { 
  editable: false;
};

const testFalse: Props = { // position not required
  editable: false
}
    
const testTrue: Props = { // position mandatory
  editable: true,
  position: MatrixEnum
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM