Search code examples
reactjsmapboxreact-map-gl

Why does the Geolib package's getCenter() function return Type 'false | { longitude: number; latitude: number; }'


As shown on the geolib package website the geolib getCenter() function is supposed to return an object like below:

{ latitude: 52.516272, longitude: 13.377722 }

The function I have written is:

 const centerMap = getCenter([markerLocation, props.actualCoordinates])

this returns in the console log:

{longitude: -26.34202029125202, latitude: 56.5658246216444}

however when I try to console log centerMap.longitude I get this error:

Property 'longitude' does not exist on type 'false | { longitude: number; latitude: number; }'.

Property 'longitude' does not exist on type 'false'.ts(2339)

Does anyone have an idea of why it is returning more than an object, is there a way around this?


Solution

  • It can return false as you can see in the source code

    It happens when points argument is not an array or it's an empty array

    Seems like they didn't bother to include that in the example

    You can try checking it it's not falsy

    const centerMap = getCenter([markerLocation, props.actualCoordinates])
    if (!centerMap) {
      throw new Error('points is an empty array')
    }
    centerMap.longitude // will work here
    

    or

    const centerMap = getCenter([markerLocation, props.actualCoordinates])
    if (centerMap) {
      centerMap.longitude // will work here
    }
    

    or you can cast

    const centerMap = getCenter([markerLocation, props.actualCoordinates]) as { longitude: number; latitude: number; }
    

    But I fill like the library should throw an error instead of returning false in such cases