Issue
I have this kind of interface
export interface IButton {
label: string;
withIcon?: boolean;
underlined?: boolean;
selected?: boolean;
iconName?: string;
isLink?: boolean;
href?: string;
onCLick?: () => void;
}
Is it possible to make conditionally the use of iconName based on the use of withIcon ?
To make an example:
<Button label='test' /> ---> this should not throw error
<Button withIcon /> this should throw an error that alert me that iconName is missing.
Solution
You can achieve this by creating Union type of icon options as follows:
type IconOptions = { withIcon?: false; iconName?: string; } | { withIcon: true; iconName: string; }
What this means is that when withIcon is true, iconName will be required, otherwise it is not required.
You can then append this type as an intersection to IButton which will also need to be a type:
export type IButton = {
label: string;
underlined?: boolean;
selected?: boolean;
isLink?: boolean;
href?: string;
onCLick?: () => void;
} & IconOptions;
Playground link.
Answered By - Ovidijus Parsiunas
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.