如何为结合MaterialUI、styled-components的Formik useField Hook设置正确TS类型
正确类型设置方案
问题根因
你之前的写法报错的核心原因是:typeof TextField获取的是styled组件本身的函数类型,而非组件接收的props类型,和FieldProps交叉后类型匹配完全不符合预期,才会抛出TS2322错误。要获取组件的props类型,必须使用TS内置的React.ComponentProps<typeof 组件>工具类型。
完整实现代码
import { useField, FieldConfig } from 'formik'; import { TextField as MuiTextField } from '@mui/material'; import styled from 'styled-components'; import { spacing } from '@mui/system'; // 自定义styled封装的TextField const TextField = styled(MuiTextField)<{ my?: number }>(spacing); // 组合类型:同时包含MUI自定义输入框的所有属性 + Formik Field的配置属性 type FormikInputProps = React.ComponentProps<typeof TextField> & FieldConfig; export const FormikInput: React.FC<FormikInputProps> = (props) => { const [field, meta] = useField(props); return ( <TextField {...field} {...props} // 错误状态优先级最高 error={meta.touched && Boolean(meta.error)} // 有错误时显示错误信息,无错误时保留用户传入的helperText helperText={meta.touched && meta.error ? meta.error : props.helperText} /> ); };
补充说明
FieldConfig是Formik内部定义的useField入参类型,包含name、validate等Formik专属字段,完全覆盖你之前用到的FieldAttributes能力- 如果你需要严格限制额外属性,可以把
FieldConfig替换为Pick<FieldConfig, 'name' | 'validate' | 'value'>等你实际用到的字段,进一步收窄类型
内容的提问来源于stack exchange,提问作者Nelson Fleig
相关产品推荐
相关产品推荐

