TypeScript报错:访问步骤对象defaultValues属性提示不存在
问题
我定义了STEPS_CONFIG对象用于描述各类步骤配置,部分步骤包含defaultValues属性,但从currentStep对象访问该属性时,TypeScript报错提示该属性不存在于对应类型中。
相关代码:
export const STEPS = { ... } as const; // 完整STEPS_CONFIG代码省略 const currentStep = STEPS_CONFIG()[stepLabels[activeStep] as keyof typeof STEPS]; const methods = useForm({ mode: 'all', defaultValues: currentStep.defaultValues, });
报错信息:
Property 'defaultValues' does not exist on type '{ title: string; description: string; properties: { boxTitle: string; rulesList: string[]; image: string; correctionImage: { image_url: string; message: string; } | undefined; selfieMode: boolean; enabled: boolean; }; onSubmit: (data: any) => Promise<any>; }'.
解决方法
1. 用类型守卫判断属性存在性
访问defaultValues前先检查属性是否存在,让TypeScript识别当前步骤的类型:
const methods = useForm({ mode: 'all', defaultValues: 'defaultValues' in currentStep ? currentStep.defaultValues : undefined, });
如果需要更严谨的类型校验,可以自定义类型谓词:
// 定义带默认值的步骤类型 type StepWithDefaults = typeof currentStep & { defaultValues: Record<string, unknown> }; // 类型守卫函数 function hasDefaultValues(step: typeof currentStep): step is StepWithDefaults { return 'defaultValues' in step; } // 使用类型守卫 const methods = useForm({ mode: 'all', defaultValues: hasDefaultValues(currentStep) ? currentStep.defaultValues : undefined, });
2. 非空类型断言(谨慎使用)
如果能100%确定当前currentStep包含defaultValues,可以用非空断言跳过类型检查:
const methods = useForm({ mode: 'all', defaultValues: currentStep.defaultValues!, });
注意:这种方法会绕过TypeScript的类型校验,后续步骤结构变更时容易出现运行时错误,仅在属性必然存在时使用。
3. 完善STEPS_CONFIG的类型定义
给STEPS_CONFIG返回的对象定义精确的联合类型,明确区分带/不带defaultValues的步骤:
// 基础步骤类型 type BaseStep = { title: string; description: string; properties: { boxTitle: string; rulesList: string[]; image: string; correctionImage: { image_url: string; message: string; } | undefined; selfieMode: boolean; enabled: boolean; }; onSubmit: (data: any) => Promise<any>; }; // 带默认值的步骤类型 type StepWithDefaults = BaseStep & { defaultValues: Record<string, unknown>; }; // 步骤配置的联合类型 type StepConfig = BaseStep | StepWithDefaults; // 给STEPS_CONFIG指定返回类型 function STEPS_CONFIG(): Record<keyof typeof STEPS, StepConfig> { // 你的配置实现 return { ... }; }
这样TypeScript就能自动识别部分步骤包含defaultValues,再结合类型守卫使用就不会报错了。
内容的提问来源于stack exchange,提问作者Ali Ehyaie
相关产品推荐
相关产品推荐

