I have define a type like below
export type InputType = {
configJsonUrl?: string;
configJsObject?: DataType;
rawData?: { [key: string]: string };
action?: () => void;
};
export type DataType = {
id: string;
type: string;
'product-configuration': { input: string };
};
For the InputType
, even though all of the 3 values of optional(configJsonUrl
, configJsObject
& rawData
) by themselves, st least one of these should be there in the React Component I am using this type in as shown in the examples below.
<ComponentX configJsonUrl='./data/info.json' />);
<ComponentX configJsObject={jsObject} />);
<ComponentX rawData={adhocData} />);
How to make one of these mandatory?
I am aware that I can make these mandatory probably like so
export type InputType = {
input: string|DataType|{ [key: string]: string }
action?: () => void;
};
However, I want them to have separate names as well (configJsonUrl
, configJsObject
& rawData
) since I use these names to do some conditional rendering.
How to achieve this? Is it even possible in TS? Please guide.
Update Currently I am doing so in my react component
const FormGenerator = ({
configJsonUrl,
configJsObject,
rawData,
}: InputType ): JSX.Element => {
const [propForForm, setPropForForm] = useState<string>('dummy');
const [loading, setLoading] = useState(false);
useEffect(() => {
if (configJsonUrl) {
setPropForForm("URL");
setLoading(false); // Stop loading
} else if (rawData) {
setPropForForm("adhoc object");
setLoading(false); // Stop loading
} else if (configJsObject) {
setPropForForm("JS object");
setLoading(false); // Stop loading
}
}, [configJsonUrl, rawData, configJsObject]);
//rest of the rendering logic
Update2
Based on suggestions by Bergi , the InputType
will become
export type InputType = {
input: {configJsonUrl: string} | {configJsObject: DataType} | {rawData: {[key: string]: string}}
action?: () => void;
};
The react component will change to
const FormGenerator = ({input}: InputType )
//rest of the rendering logic
How to access (configJsonUrl
, configJsObject
& rawData
) from the input
?