【问题标题】:How to properly use formik.values in map for typescript?如何在 map 中正确使用 formik.values 进行打字稿?
【发布时间】:2021-08-19 18:58:16
【问题描述】:

我在将 useFormik 用于 typescript 时遇到了一个错误,有人可以帮忙吗?非常感谢。

const value = formik.values[field.name]; 行中,我收到此错误: 元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“{名称:字符串;描述:字符串;颜色:字符串; }'。

const fields = [
  {name: 'name', label: 'GENERAL.NAME'},
  {name: 'description', label: 'GENERAL.DESC'},
  {name: 'color', label: 'GENERAL.COLOR'}
];

export const Create: React.FC = () => {
  const {loading} = useSelector<RootState>(
    (state) => state.calendarReducer,
    shallowEqual
  ) as CalendarState;

  const formik = useFormik({
    enableReinitialize: true,
    initialValues: {name: '', description: '', color: Constants.COLORS.AppleRed},
    onSubmit: (values) => {
      console.log(values);
    }
  });

  return (
    <form className='form' onSubmit={formik.handleSubmit}>
      {fields.map((field, index) => {
        const value = formik.values[field.name];
        return (
          <div
            key={index}
            className='sm-6 md-4 lg-3 my-3 d-flex justify-content-between align-items-center'
          >
            <label className=''>
              <FormattedMessage id={field.label} />
            </label>
            <TextField
              disabled={loading}
              fullWidth={false}
              name={field.name}
              onChange={formik.handleChange}
              value={'xxxxxx'}
              variant='standard'
            />
          </div>
        );
      })}
    </form>
  );
};

the code here

【问题讨论】:

    标签: typescript formik


    【解决方案1】:

    您可以使用const 断言将fields 指定为文字值。

    type Values = {
      name: string;
      description: string;
      color: string;
    }
    declare const values: Values;
    
    const fields = [
      {name: 'name', label: 'GENERAL.NAME'},
      {name: 'description', label: 'GENERAL.DESC'},
      {name: 'color', label: 'GENERAL.COLOR'}
    ] as const;
    
    fields.map((field) => values[field.name]); // no error
    

    【讨论】:

    • 它有效。非常感谢!你能告诉我更多信息为什么会这样吗?看不懂。。
    • 如果您删除 as const 并将鼠标悬停在 fields 上,您将看到类型为 { name: string; label: string; }[]。但是,使用 as const,TypeScript 将更具体地了解 namelabel 值的类型(尝试悬停在 as const 上)。
    猜你喜欢
    • 1970-01-01
    • 2021-12-21
    • 2019-03-21
    • 1970-01-01
    • 1970-01-01
    • 2020-07-20
    • 2020-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多