Issue
I'm creating a Typescript app that takes an address from the user and displays it on a Google map.
I've created a type GoogleGeocodingResponse that accepts the GeoCoding response.data.results as {geometry: {location: {lat: Number; lng: Number}}}
Then I use Axios to:
.get<GoogleGeocodingResponse>(
`https://maps.googleapis.com/maps/api/geocode/json?
address=${encodeURI(enteredAddress)}&key=${GOOGLE_API_KEY}`
)
The part I don't get is, how can I use this data to create a LatLng? I've been using:
const coordinates = new google.maps.LatLng({
lat: Number(response.data.results[0].geometry.location.lat),
lng: Number(response.data.results[0].geometry.location.lng),
})
Casting to type Number works, but it seems I should be able to get the data directly from the GoogleGeocodingResponse without having to cast first. Do I have to specifically define a type? Is there a type in @types/google.maps I can use? Something else?
Solution
You should not mix the type Number with number.
Type
Numberis not assignable to typenumber.numberis a primitive, butNumberis a wrapper object. Prefer usingnumberwhen possible.
{geometry: {location: {lat: number; lng: number}}} (N -> n)
I have tested it. It works. You should always use the primitive types (lowercase). No cast necessary anymore. You could also just use as number behind your assignment if you want. But I recommend to change your type from Number to number.
Solution A (recommended):
// Use primitive types.
type YourType = { geometry: { location: { lat: number; lng: number } } };
Solution 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,
})
Btw. your solution of Number(value) only works because Number returns the type number (primitive / lowercase).
Read more of TypeScript Do's and Don'ts.
❌ Don’t ever use the types Number, String, Boolean, Symbol, or Object These types refer to non-primitive boxed objects that are almost never used appropriately in JavaScript code.
✅ Do use the types number, string, boolean, and symbol.
Answered By - Dominik
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.