Ionic使用agm-direction时waypoints出现类型不匹配报错如何解决
问题现象
使用agm-direction时,Visual Studio Code在模板的[waypoints]属性处报类型错误,实际运行功能正常,需要消除编辑器告警。
报错信息如下:
Type '{ location: { lat: number; lng: number; }; }[]' is not assignable to type 'DirectionsWaypoint[]'. Type '{ location: { lat: number; lng: number; }; }' is not assignable to type 'DirectionsWaypoint'. Types of property 'location' are incompatible. Type '{ lat: number; lng: number; }' is not assignable to type 'string | Place | LatLng'. Type '{ lat: number; lng: number; }' is missing the following properties from type 'LatLng': equals, toUrlValue, toJSON
现有代码
Typescript代码
waypoints = [ {location: { lat: -25.913330, lng: 28.185640 }}, {location: { lat: -25.869650, lng: 28.217950 }} ];
HTML模板代码
<agm-direction [origin]="origin" [destination]="destination" [waypoints]="waypoints"></agm-direction>
解决方法
- 方法1:模板侧直接消告警(最快,无需修改业务代码)
直接修改HTML中[waypoints]绑定的内容,用$any()包裹变量绕过类型检查:
<agm-direction [origin]="origin" [destination]="destination" [waypoints]="$any(waypoints)"></agm-direction>
- 方法2:符合类型规范的写法(无类型隐患,推荐)
把经纬度对象替换为官方LatLng实例,匹配类型定义要求:
waypoints = [ {location: new google.maps.LatLng(-25.913330, 28.185640)}, {location: new google.maps.LatLng(-25.869650, 28.217950)} ];
- 方法3:TS侧类型断言(折中方案,适用于不方便修改原始数据结构的场景)
给变量加上DirectionsWaypoint类型声明+断言,告知TS编译器该结构符合要求:
import { DirectionsWaypoint } from '@agm/direction'; waypoints: DirectionsWaypoint[] = [ {location: { lat: -25.913330, lng: 28.185640 }}, {location: { lat: -25.869650, lng: 28.217950 }} ] as DirectionsWaypoint[];
内容的提问来源于stack exchange,提问作者Vassilis
相关产品推荐
相关产品推荐

