[英]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
。 如果editable
為true
,則存在 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.