Creating a custom type called InputType
with optional properties like this:
export type InputType = {
configJsonUrl?: string;
configJsObject?: DataType;
rawData?: { [key: string]: string };
action?: () => void;
};
export type DataType = {
id: string;
type: string;
'product-configuration': { input: string };
};
In the InputType
, at least one of the optional values (configJsonUrl
, configJsObject
, or rawData
) should be present when using this type in a React Component as shown in the examples below.
<ComponentX configJsonUrl='./data/info.json' />);
<ComponentX configJsObject={jsObject} />);
<ComponentX rawData={adhocData} />);
How can you make one of these options mandatory?
To accomplish this without merging properties, you could define the InputType
like this:
export type InputType = {
input: string|DataType|{ [key: string]: string }
action?: () => void;
};
However, if you want to keep separate names for each property (configJsonUrl
, configJsObject
, and rawData
), is it possible in TypeScript? Can anyone provide guidance?
Update: In your react component, you are currently implementing it like this:
const FormGenerator = ({
configJsonUrl,
configJsObject,
rawData,
}: InputType ): JSX.Element => {
const [propForForm, setPropForForm] = useState<string>('dummy');
const [loading, setLoading] = useState(false);
// Further logic here
Update2:
Following suggestions from others, adjust the InputType
definition to:
export type InputType = {
input: {configJsonUrl: string} | {configJsObject: DataType} | {rawData: {[key: string]: string}}
action?: () => void;
};
Alter the react component accordingly:
const FormGenerator = ({input}: InputType )
// Additional rendering logic here
How do you access configJsonUrl
, configJsObject
, and rawData
from the input
object?