Material UI Autocomplete中getOptionLabel类型错误问题求助
解决Material UI Autocomplete的TypeScript类型错误问题
问题场景
定义了如下常量数组:
const Reference = [ { label: "RF-100", year: "Test" }, { label: "RF-200", year: "Test2" }, { label: "RF-300", year: "Test3" }, ];
编写Material UI的Autocomplete组件时,希望通过getOptionLabel渲染label - year格式的选项文本(例如RF-100 - Test),但添加getOptionLabel={(option) => ${option.label}}后出现以下TypeScript错误:
Property 'label' does not exist on type 'string | { label: string; year: string; }'. Property 'label' does not exist on type 'string'
解决方案
该错误源于TypeScript无法自动推断options的具体类型,默认将选项类型判定为string | { label: string; year: string; },导致访问option.label时触发类型校验报错。可通过以下三种方式解决:
1. 显式定义数组类型
给Reference数组指定明确的接口类型,让TypeScript准确识别选项结构:
// 定义选项结构的接口 interface ReferenceOption { label: string; year: string; } // 为数组指定类型 const Reference: ReferenceOption[] = [ { label: "RF-100", year: "Test" }, { label: "RF-200", year: "Test2" }, { label: "RF-300", year: "Test3" }, ];
2. 给Autocomplete组件指定泛型类型
直接在Autocomplete组件上声明泛型,明确选项的具体类型:
export const Auto: React.FC = () => { return ( <Autocomplete<{ label: string; year: string }> id="Combox-demo" options={Reference} getOptionLabel={(option) => `${option.label} - ${option.year}`} style={{ width: 300 }} renderInput={(params) => <TextField {...params} label="Combo box" variant="outlined" prefix="RF" />} /> ); };
3. 在getOptionLabel中使用类型断言
若不想额外定义类型,可在getOptionLabel中对option做类型断言,明确告知TypeScript它是包含label和year的对象:
getOptionLabel={(option) => { const { label, year } = option as { label: string; year: string }; return `${label} - ${year}`; }}
推荐优先使用前两种方式,类型定义更清晰,代码可读性和可维护性更高。
内容的提问来源于stack exchange,提问作者Jason_Hough
相关产品推荐
相关产品推荐

