TypeScript报错:自定义组件无法访问MUI-base InputUnstyled的maxLength属性
解决MUI-base InputUnstyled自定义组件访问maxLength的TypeScript报错问题
问题核心
SlotComponentProps的默认类型未自动包含原生input的全部属性(如maxLength),且componentProps可能是返回props的函数,直接访问会触发类型校验错误。
具体解决方法
1. 先解析componentProps为实际props对象
componentProps可能是函数或对象,需先处理成可直接访问的对象:
// 先处理componentProps,得到最终的props对象 const resolvedInputProps = typeof componentProps === 'function' ? componentProps(ownerState) : componentProps;
2. 补充类型定义,包含原生input属性
通过TypeScript的类型断言或扩展类型,让编译器识别原生input的属性:
import { InputHTMLAttributes } from 'react'; // 断言resolvedInputProps包含原生input的属性 const maxLength = (resolvedInputProps as InputHTMLAttributes<HTMLInputElement>).maxLength;
或者直接在组件的类型定义中合并原生input属性:
import { InputHTMLAttributes } from 'react'; import { InputUnstyledProps } from '@mui/base/InputUnstyled'; // 自定义组件props,合并原生input属性 type CustomInputProps = InputUnstyledProps & InputHTMLAttributes<HTMLInputElement>; const CustomInput = (props: CustomInputProps) => { // 直接从props中获取maxLength,无需从componentProps里取 const { maxLength, ...restProps } = props; // 后续逻辑 return <InputUnstyled {...restProps} />; };
3. 更简洁的类型复用
使用ComponentPropsWithoutRef直接获取原生input的完整类型:
import { ComponentPropsWithoutRef } from 'react'; type NativeInputProps = ComponentPropsWithoutRef<'input'>; // 处理后访问maxLength const maxLength = (resolvedInputProps as NativeInputProps).maxLength;
关键提示
- 必须先处理
componentProps的函数情况,确保拿到的是最终props对象 - 通过类型扩展或断言,让TypeScript识别原生input的属性集合
内容的提问来源于stack exchange,提问作者K.Nes
相关产品推荐
相关产品推荐

