[英]Conditional boolean type in typescript with interface
How would I write conditional boolean type for this?我将如何为此编写条件布尔类型?
ie 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;
}
I use props like this我用这样的道具
const SheetsCell: React.FC<MainProps> = ({
editable,
value,
textType = "normal",
classNames = "",
position,
...
Here if something is editable, I want the type of position to be Sheets.Matrix
else, position isn't required.在这里,如果某些内容是可编辑的,我希望位置类型为
Sheets.Matrix
否则,不需要位置。
One way to do it is using an interface and the intersection operator( &
).一种方法是使用接口和交集运算符 (
&
)。
You can use an intersection type , which combines multiple types into one.您可以使用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;
};
The above type MainProps
forces editable
to be true
in one case and false
in another.上面的
MainProps
类型强制editable
在一种情况下为true
,在另一种情况下为false
。 If editable
is true
, then position property exists and if it is false,
position property exists but it is not required.如果
editable
为true
,则存在 position 属性;如果为false,
则存在 position 属性但不是必需的。
unions is used above, to generate a type which can be one of the two values.上面使用unions来生成可以是两个值之一的类型。
MainProps
can be one of the two types (both being intersection with Props
type). MainProps
可以是两种类型之一(都是与Props
类型的交集)。
Here is the playground link这是游乐场链接
You could use type aliases instead of an interface eg您可以使用类型别名而不是接口,例如
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.