TypeScript封装MUI TextField时使用...otherProps报错的解决求助
{...otherProps}时的API限制错误 在TypeScript封装Material UI的TextField组件时,使用{...otherProps}传递剩余属性会触发错误提示:
"The TextField is a convenience wrapper for the most common cases (80%). It cannot be all things to all people, otherwise the API would grow out of control."
移除{...otherProps}错误消失,但需要保留该语法传递额外属性,以下是可行的解决方法:
方案1:按组件层级拆分属性
Material UI的TextField是上层封装组件,底层Input的属性需要通过InputProps传递,而非直接挂载到TextField上。你可以拆分otherProps,把属性分发到正确的层级:
import TextField from '@material-ui/core/TextField'; import ErrorMessage from '../ErrorMessage'; import { InputProps as TextFieldProps } from '../../../model'; import { InputProps as MuiInputProps } from '@material-ui/core/Input'; const TextFieldWrapper = (props: TextFieldProps) => { const { name, type, valid, touched, errorMessage, ...otherProps } = props; // 分离TextField自身支持的属性和需要传给底层Input的属性 const { InputProps: incomingInputProps, ...textFieldProps } = otherProps; return ( <> <TextField name={name} type={type} variant="outlined" {...textFieldProps} InputProps={{ ...incomingInputProps, // 如需自定义输入组件,在此处传递(比如你的MaskedInput) // inputComponent: (inputProps: MuiInputProps) => <MaskedInput {...inputProps} /> }} /> {!valid && touched && <ErrorMessage>{errorMessage}</ErrorMessage>} </> ); }; export default TextFieldWrapper;
方案2:用TypeScript类型约束过滤无效属性
如果你的TextFieldProps包含了TextField不支持的属性,通过类型工具过滤出仅TextField兼容的属性:
import TextField, { TextFieldProps as MuiTextFieldProps } from '@material-ui/core/TextField'; import ErrorMessage from '../ErrorMessage'; import { InputProps as TextFieldProps } from '../../../model'; // 仅保留MUI TextField支持的属性,同时保留自定义的校验相关属性 type ValidTextFieldProps = Pick<TextFieldProps, keyof MuiTextFieldProps> & { valid?: boolean; touched?: boolean; errorMessage?: string }; const TextFieldWrapper = (props: ValidTextFieldProps) => { const { valid, touched, errorMessage, ...textFieldProps } = props; return ( <> <TextField variant="outlined" {...textFieldProps} // 仅传递TextField支持的属性 /> {!valid && touched && <ErrorMessage>{errorMessage}</ErrorMessage>} </> ); }; export default TextFieldWrapper;
方案3:临时禁用ESLint规则(不推荐)
如果上述方案不适用,可针对该行禁用Material UI的ESLint校验规则,但这会跳过API合法性检查,可能引发潜在问题:
// eslint-disable-next-line @material-ui/no-restricted-props <TextField name={name} type={type} variant='outlined' {...otherProps}/>
错误原因说明
这个提示是Material UI的ESLint规则@material-ui/no-restricted-props触发的,目的是避免给TextField传递它不直接支持的属性——因为TextField是封装组件,很多属性需要通过InputProps、FormHelperTextProps等嵌套属性传递,直接展开会导致API结构混乱。
内容的提问来源于stack exchange,提问作者Praveen

