使用@react-google-maps/api+Typescript遇InfoBox类型错误:number无法赋值给()=>number
使用@react-google-maps/api结合TypeScript时的类型错误问题
问题场景
项目迁移到TypeScript后,使用@react-google-maps/api的InfoBox组件出现类型错误,此前JavaScript版本完全正常。尝试添加// @ts-expect-error抑制错误但未生效。
代码示例
<InfoBox // @ts-expect-error className={classnames('info-box', { 'visible': selectedMarker === checkpoint.checkpoint_id })} position={{ lat: checkpoint.lat, lng: checkpoint.lng }} options={{ closeBoxURL: ``, enableEventPropagation: true, pixelOffset: new window.google.maps.Size(-16, -110) }} >
错误提示
No overload matches this call. Overload 2 of 2, '(props: InfoBoxProps, context: any): InfoBoxComponent', gave the following error. Type 'number' is not assignable to type '() => number'. Overload 2 of 2, '(props: InfoBoxProps, context: any): InfoBoxComponent', gave the following error. Type 'number' is not assignable to type '() => number'.ts(2769)
问题解析与修复方案
1. 错误含义
错误提示表明你给两个属性传了直接的数字值,但这两个属性的TypeScript类型要求是返回数字的函数,类型不匹配导致报错。
2. 定位并修复错误
结合代码和@react-google-maps/api的类型定义,最可能的问题出在position属性:部分版本的库中,InfoBox的position允许传入函数类型的坐标,静态坐标值触发了类型校验冲突。
尝试将position改为函数形式返回坐标:
position={() => ({ lat: checkpoint.lat, lng: checkpoint.lng })}
如果checkpoint.lat或checkpoint.lng存在可能为undefined的情况,可添加非空断言(前提是你能保证值一定存在):
position={() => ({ lat: checkpoint.lat!, lng: checkpoint.lng! })}
3. 为什么// @ts-expect-error无效
// @ts-expect-error必须紧挨着存在错误的代码行才能生效。你的注释放在className属性上方,但实际错误出在position或其他属性行,因此注释没有覆盖到错误位置,无法抑制报错。
内容的提问来源于stack exchange,提问作者xyz83242
相关产品推荐
相关产品推荐

