使用react-bootstrap-typeahead遇类型错误:Property 'name'不存在于类型'Option'
问题
在React应用中使用react-bootstrap-typeahead组件实现演员搜索功能时,遇到错误:Property 'name' does not exist on type 'Option'。
相关代码
组件代码:
import { Typeahead } from "react-bootstrap-typeahead"; import { actorMovieDTO } from "../actors/actors.model"; interface typeAheadActorsProps{ displayName:string; actors: actorMovieDTO[]; } function TypeAheadActors(props: typeAheadActorsProps){ const actors: actorMovieDTO[]=[{ id:1, name: "Felipe", character: '',picture:'' }, { id:2, name: "Fernando", character: '', picture:'' }, { id:3, name: "Jesica", character: '', picture:'' }] return( <> <label>{props.displayName}</label> <Typeahead id="typeahead" onChange={actor => { console.log(actor); } } options={actors} labelKey={actor=> actor.name} filterBy={['name']} placeholder="write the name of the actor...." > </Typeahead> </> )}export default TypeAheadActors
actors.model文件代码:
export interface actorMovieDTO{ id:number; name: string; character: string; picture: string;}
错误出现在labelKey={actor=> actor.name}处,明明actorMovieDTO接口中存在name属性,且已正确导入,使用的是组件最新版本,该如何修复?
解决方案
这个错误是TypeScript类型推断缺失导致的,react-bootstrap-typeahead默认将options的类型推断为通用Option类型,无法识别自定义的actorMovieDTO结构,只需显式给组件指定泛型类型即可解决:
- 为Typeahead添加泛型参数
修改组件使用代码,明确指定泛型为actorMovieDTO:
<Typeahead<actorMovieDTO> id="typeahead" onChange={(selectedActors) => { console.log(selectedActors); }} options={actors} labelKey={actor=> actor.name} filterBy={['name']} placeholder="write the name of the actor...." > </Typeahead>
注意:onChange的参数本质是选中项的数组(即使是单选模式),所以参数名改为selectedActors更贴合实际,此时TypeScript会自动识别其类型为actorMovieDTO[]。
- 验证修复效果
添加泛型后,TypeScript能正确识别labelKey回调中actor的类型为actorMovieDTO,不会再报错name属性不存在。
另外,你代码中同时定义了本地actors数组和props接收的actors,如果是测试用途可保留,实际业务场景建议直接使用props.actors作为options的值。
内容的提问来源于stack exchange,提问作者Hasith Yoman
相关产品推荐
相关产品推荐

