React 18中使用react-bootstrap-typeahead 5.1.8遇类型错误求助
解决react-bootstrap-typeahead 5.1.8在React18中的类型错误
问题原因
TypeScript无法自动推断Typeahead组件的选项类型,默认将labelKey的参数类型识别为string | Option,导致无法访问actor.name属性。
修复方案
给Typeahead组件显式指定泛型类型为actorMovieDTO,让TypeScript明确选项的结构:
import { Typeahead } from "react-bootstrap-typeahead"; import { actorMovieDTO } from "../actors/actors.model"; export default function TypeAheadActors(props: typeAheadActorsProps) { const actors: actorMovieDTO[] = [{ id: 1, name: 'Felipe', character: '', picture: '' }, { id: 2, name: 'Fernando', character: '', picture: '' }, { id: 3, name: 'Jessica', character: '', picture: '' }] return ( <> <label>{props.displayName}</label> {/* 显式指定泛型类型actorMovieDTO */} <Typeahead<actorMovieDTO> id="typeahead" onChange={(selectedActors) => { // 注意:onChange返回的是选中项数组,即使单选也是数组 console.log(selectedActors[0]); }} options={actors} labelKey={actor => actor.name} filterBy={['name']} placeholder="Write the name of the actor..." minLength={1} /> </> ) } interface typeAheadActorsProps { displayName: string; actors: actorMovieDTO[]; }
额外说明
onChange回调默认返回选中项的数组(无论组件是否设置为多选),如果是单选场景,需要取数组的第一个元素。- 显式指定泛型后,TypeScript能正确识别选项的属性,直接解决
Property 'name' does not exist的类型错误。
内容的提问来源于stack exchange,提问作者Rustam
相关产品推荐
相关产品推荐

