使用MUI Autocomplete组件时遭遇TypeScript类型错误求助
问题场景
按照MUI文档示例构建的Autocomplete组件代码:
<Autocomplete disablePortal id="combo-box-demo" options={allGroups} sx={{ width: 300 }} renderInput={(params) => <TextField {...params} label="Groups" />} />
出现的类型错误信息:
Type '"small" | undefined' is not assignable to type 'OverridableStringUnion<"small" | "medium", TextFieldPropsSizeOverrides>'.
Type 'undefined' is not assignable to type 'OverridableStringUnion<"small" | "medium", TextFieldPropsSizeOverrides>'.ts(2375)
问题根源
这不是MUI源码的类型定义问题,而是TypeScript严格模式下的校验冲突:Autocomplete传给renderInput的params中,size参数可能为undefined,但TextField的size属性要求必须是"small"或"medium"(不允许为undefined)。
解决办法
1. 显式指定size属性
直接覆盖params里的size值,传入合法的固定参数:
<Autocomplete disablePortal id="combo-box-demo" options={allGroups} sx={{ width: 300 }} renderInput={(params) => ( <TextField {...params} label="Groups" size="medium" /> )} />
2. 过滤undefined的size参数
通过解构赋值排除可能为undefined的size,再传递剩余参数给TextField,此时组件会使用默认size值:
<Autocomplete disablePortal id="combo-box-demo" options={allGroups} sx={{ width: 300 }} renderInput={({ size, ...rest }) => ( <TextField {...rest} label="Groups" /> )} />
3. 放宽TypeScript校验(不推荐)
如果项目可以接受降低类型安全性,可在tsconfig.json中设置strictNullChecks: false,但这会影响整个项目的类型校验严谨性。
替代组件
除了TextField,还可以使用MUI的以下组件作为renderInput的返回值,它们对参数的类型限制更适配Autocomplete的params:
import OutlinedInput from '@mui/material/OutlinedInput'; import InputLabel from '@mui/material/InputLabel'; import FormControl from '@mui/material/FormControl'; <Autocomplete disablePortal id="combo-box-demo" options={allGroups} sx={{ width: 300 }} renderInput={(params) => ( <FormControl> <InputLabel>Groups</InputLabel> <OutlinedInput {...params} label="Groups" /> </FormControl> )} />
也可以根据需求选择FilledInput或基础的Input组件。
内容的提问来源于stack exchange,提问作者tprebenda

