Reputation: 1796
I am trying to convert my NodeJS JavaScript code to a TypeScript NodeJS base which is then converted to JavaScript when NodeJS runs. Helps me to keep types clear and some other helpful stuff JavaScript is missing.
I have a function which I call to geocode an address which works in JavaScript fine but in typescript I get the error that its not a function.
import * as googleMapsClient from "@google/maps";
googleMapsClient.createClient({ key: "AIzaSyC0HCjjidjijijes1sbMLG5k"});
export function geocodeAddress( address) {
return new Promise((resolve) => {
googleMapsClient.geocode({
address
}, (err, response) => {
if (!err) {
resolve(response.json.results[0]);
}
});
});
}
the same code in which works in JavaScript looks like this
const googleMapsClient = require('@google/maps').createClient({
key: 'AIzaSyC0HC2Turfkrofrofkroes1sbMLG5k'
});
function geocodeAddress(address){
return new Promise(resolve =>{
googleMapsClient.geocode({
address: address
}, function(err, response) {
if (!err) {
//console.log(response.json.results[0].geometry)
resolve(response.json.results[0])
}
})
})}
module.exports = {
geocodeAddress :geocodeAddress
}
in typeScript it complains about Promise
TypeError: googleMapsClient.geocode is not a function
at Promise (C:\nodeRoot\CRMLS-IMPORT\dist\helper\geocoding.js:27:26)
at new Promise (<anonymous>)
at Object.geocodeAddress (C:\nodeRoot\CRMLS-IMPORT\dist\helper\geocoding.js:26:12)
at Object.<anonymous> (C:\nodeRoot\CRMLS-IMPORT\dist\app.js:107:38)
at Generator.next (<anonymous>)
at C:\nodeRoot\CRMLS-IMPORT\dist\app.js:7:71
at new Promise (<anonymous>)
at __awaiter (C:\nodeRoot\CRMLS-IMPORT\dist\app.js:3:12)
at app.get (C:\nodeRoot\CRMLS-IMPORT\dist\app.js:105:40)
at Layer.handle [as handle_request] (C:\nodeRoot\CRMLS-IMPORT\node_modules\express\lib\router\layer.js:95:5)
Upvotes: 0
Views: 105
Reputation: 1796
Thanks to @Romen i figured it out, below is the fix now it works as the JS code..
import * as MapsClient from "@google/maps";
const googleMapsClient = MapsClient.createClient({ key: "AIzaSyC0HC2Tuekjrekfjkfj1sbMLG5k"});
Upvotes: 1
Reputation: 1776
In JS you are assigning the return value of createClient()
to the googleMapsClient
:
const googleMapsClient = require('@google/maps').createClient({
key: 'AIzaSyC0HC2Turfkrofrofkroes1sbMLG5k'
});
In TS you are assigning the module's exports to googleMapsClient
:
import * as googleMapsClient from "@google/maps";
In the JS version you can call googleMapsClient.geocode()
because the function exists in the client object returned from createClient()
.
In the TS version you can't call googleMapsClient.geocode()
because googleMapsClient
is not a client object, it is the module.
Change your TS to this:
import * as googleMaps from "@google/maps";
const googleMapsClient = googleMaps.createClient({
key: 'AIzaSyC0HC2Turfkrofrofkroes1sbMLG5k'
});
Upvotes: 3