【问题标题】:Typescript types problem with Google Maps LatLng{}Google Maps LatLng 的 Typescript 类型问题{}
【发布时间】:2021-11-10 21:20:52
【问题描述】:

我正在创建一个 Typescript 应用程序,它从用户那里获取地址并将其显示在 Google 地图上。

我创建了一个type GoogleGeocodingResponse,它接受地理编码response.data.results 作为{geometry: {location: {lat: Number; lng: Number}}}

然后我用 Axios 来:

.get<GoogleGeocodingResponse>(
      `https://maps.googleapis.com/maps/api/geocode/json? 
   address=${encodeURI(enteredAddress)}&key=${GOOGLE_API_KEY}`
 )

我不明白的部分是,如何使用这些数据创建LatLng?我一直在使用:

const coordinates = new google.maps.LatLng({
  lat: Number(response.data.results[0].geometry.location.lat),
  lng: Number(response.data.results[0].geometry.location.lng),
})

强制转换为Number 有效,但似乎我应该能够直接从GoogleGeocodingResponse 获取数据,而无需先进行强制转换。我必须专门定义一个类型吗? @types/google.maps 中是否有我可以使用的类型?还有什么?

【问题讨论】:

    标签: javascript typescript google-maps typescript-types


    【解决方案1】:

    您不应将Number 类型与number 混合使用。

    类型 Number 不可分配给类型 numbernumber 是一个原始对象,但 Number 是一个包装对象。尽可能使用number

    {geometry: {location: {lat: number; lng: number}}} (N -> n)

    我已经测试过了。有用。您应该始终使用原始类型(小写)。不再需要演员。如果你愿意,你也可以在你的作业后面使用as number。但我建议将您的类型从 Number 更改为 number

    解决方案 A(推荐):

    // Use primitive types.
    type YourType = { geometry: { location: { lat: number; lng: number } } };
    

    解决方案 B:

    const coordinates = new google.maps.LatLng({
      lat: response.data.results[0].geometry.location.lat as number,
      lng: response.data.results[0].geometry.location.lng as number,
    })
    

    顺便说一句。您的Number(value) 解决方案仅有效,因为Number 返回类型number(原语/小写)。

    阅读更多TypeScript Do's and Don'ts

    ❌ 永远不要使用类型 Number、String、Boolean、Symbol 或 Object 这些类型指的是在 JavaScript 代码中几乎从未正确使用过的非原始装箱对象。

    ✅ 请务必使用数字、字符串、布尔值和符号类型。

    【讨论】:

    • 是的,完全正确@Dominik。我首先输入了错误的“YourType”,并被它返回的“Number v. number”错误消息弄糊涂了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2020-03-22
    • 1970-01-01
    • 1970-01-01
    • 2018-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-02
    相关资源
    最近更新 更多