Dealing with two APIs that have contrasting property names for longitude coordinates—lon
and lng
, I am in the process of creating a converter function to accommodate both sets of data. This way, locations from either API can be used seamlessly.
Encountering an error while implementing this function, it strikes me as a potential bug. Despite being aware of various workarounds, I am curious to delve into the root cause of this issue. Is it truly a bug, or is there a piece of the puzzle that I may be overlooking?
const fillLonLng1 = <T extends LatLng | LatLon>(loc: T): T & LatLon & LatLng => {
if ( isLatLon(loc) ) {
return {...loc, lng: loc.lon};
} else {
return {...loc, lon: loc.lng};
}
}
The error arises at the first return
statement:
Type 'T & { lng: number; lat: number; lon: number; }' is not assignable to type 'T & LatLon & LatLng'.
Type 'T & { lng: number; lat: number; lon: number; }' is not assignable to type 'LatLon'.(2322)
Although TypeScript correctly recognizes that the returned value includes both lat
and lon
properties, each with a number value, the mismatch with the LatLon
type leaves me puzzled. The definition of LatLon
is as follows:
interface LatLon {
lat: number;
lon: number;
}
const isLatLon = <T extends Partial<LatLon>>(loc: T): loc is T & LatLon => {
return loc.lat !== undefined && loc.lon !== undefined;
}
Complete Typescript Playground. Upon exploration, I discovered two alternative solutions that successfully bypass this error message without resorting to as
. One involves splitting the function into separate parts, while the other employs intricate typings.