代码const fields:magicField[] = [ { type: \'select\', RenderComponent: CustomInput, config: { label: \'First Name\', placeholder: \'First Name\',...
代码
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" },
],
},
},
];
我想将此 fields.config.name 转换为对象的键
ConvertedObj.firstName
(TypeSafe)...等等
定义类型
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;
我用谷歌搜索了一下,发现
我可以使用此类型
type ResultType = {
[K in ArrayItem['name']]: ArrayItem['value'];
};
这并没有给我类型安全
当我研究时,我发现它只在只读(作为 const)类型中工作
所以我尝试了一切
-
将 readonly 添加到每个属性
-
添加
as const
到每个属性
有效的是
-
添加
as const
至 fields.config.name
-
从字段变量中
magicFields[]
删除类型
但我想要这个结果而不删除 magicFields[]
类型