You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 13:30:00