TypeScript中如何在map循环内正确使用formik.values取值
报错的根本原因是TypeScript默认将
fields数组中的name字段推导为string类型,而formik.values的键是固定的字面量联合类型'name' | 'description' | 'color',通用string类型不能直接用来索引有明确键限制的对象,因此触发隐式any类型报错。
最优解决步骤
步骤1:定义表单值类型并给useFormik传入泛型
首先显式声明表单值的TS类型,同时给useFormik指定泛型参数,明确formik实例的类型:
// 定义表单值的类型 interface FormValues { name: string; description: string; color: string; } // 给useFormik传入泛型 const formik = useFormik<FormValues>({ enableReinitialize: true, initialValues: {name: '', description: '', color: Constants.COLORS.AppleRed}, onSubmit: (values) => { console.log(values); } });
步骤2:给fields数组限定name字段的类型
限制fields数组中每个项的name只能是FormValues的键,避免被推导为通用string:
type FieldItem = { name: keyof FormValues; label: string; } const fields: FieldItem[] = [ {name: 'name', label: 'GENERAL.NAME'}, {name: 'description', label: 'GENERAL.DESC'}, {name: 'color', label: 'GENERAL.COLOR'} ];
临时快速解决方案(不推荐长期使用)
如果只是临时绕过报错,可以直接对field.name做类型断言:
const value = formik.values[field.name as keyof typeof formik.values];
内容的提问来源于stack exchange,提问作者Roy
相关产品推荐
相关产品推荐

