You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 07:58:03