Code
const fields:magicField[] = [
{
type: "select",
RenderComponent: CustomInput,
config: {
label: "First Name",
placeholder: "First Name",
name: "firstName" ,
validation: z.string().min(1),
options: () => [
{ label: "First Name", value: "First Name" },
{ label: "Second Name", value: "Second Name" },
],
},
},
];
I want to convert this fields.config.name as the key of object
ConvertedObj.firstName
(TypeSafe)
…and so on
Defined Types
export type ValidationType = ZodString | ZodNumber | ZodEnum | ZodNativeEnum;
export type commonConfig = {
label: string;
placeholder: string;
className?: string;
readonly name: string;
disabled?:boolean
validation: ValidationType;
}
export type magicFieldSelect = {
type: "select";
config: commonConfig & magicFieldSelectConfig;
}
export type magicFieldInput = {
type: "input";
config: commonConfig & magicFieldInputConfig;
}
export type magicFieldSelectConfig = {
options: () => Promise<optionType[]> | optionType[];
};
export type magicFieldInputConfig = {
type: HTMLInputTypeAttribute;
};
export type magicField = Readonly<(magicFieldSelect | magicFieldInput) & {RenderComponent: RenderComponent}>
export type typeWithRenderField<T> = T & {
control: Control<z.infer<formSchema>>;
};
export type InputFieldWithRenderFields = Partial<typeWithRenderField<magicFieldInput["config"]>>;
export type SelectFieldWithRenderFields = Partial<typeWithRenderField<magicFieldSelect["config"]>>;
export type inputFieldWithRenderFieldFn = React.FunctionComponent<InputFieldWithRenderFields>
export type selectFieldWithRenderFieldFn = React.FunctionComponent<SelectFieldWithRenderFields>
export type RenderComponent = inputFieldWithRenderFieldFn | selectFieldWithRenderFieldFn;
I Googled it and found
I can use this types
type ResultType = {
[K in ArrayItem['name']]: ArrayItem['value'];
};
This did’t gave me the typesafety
as i was Researching i found it only work in readonly (as const) types
so i tried everything like
- adding the readonly to every property
- adding the
as const
to every property
the one that worked was
- adding the
as const
tofields.config.name
- and removing the type
magicFields[]
from the fields variable
But I want this result without removing the magicFields[]
type
New contributor
Exlaso is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.