将具有承诺的功能从JS转换为TS的问题

时间:2019-10-15 19:35:46

标签: javascript node.js typescript

我正在尝试将NodeJS JavaScript代码转换为TypeScript NodeJS基础,然后在运行NodeJS时将其转换为JavaScript。帮助我保持类型清晰,缺少JavaScript的其他有用信息。

我有一个函数,该函数可以对可以在JavaScript中正常工作的地址进行地址解析,但是在打字稿中却收到错误消息,指出它不是一个函数。

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]);
            }
        });
    });
}

在JavaScript中使用的相同代码看起来像这样

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
}

在typeScript中,它抱怨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)

2 个答案:

答案 0 :(得分:3)

在JS中,您将createClient()的返回值分配给googleMapsClient

const googleMapsClient = require('@google/maps').createClient({
    key: 'AIzaSyC0HC2Turfkrofrofkroes1sbMLG5k'
  });

在TS中,您要将模块的导出分配给googleMapsClient

import * as googleMapsClient from "@google/maps";

在JS版本中,您可以调用googleMapsClient.geocode(),因为该函数存在于从createClient()返回的客户端对象中。

在TS版本中,您无法调用googleMapsClient.geocode(),因为googleMapsClient不是客户端对象,而是模块。

将您的TS更改为此:

import * as googleMaps from "@google/maps";
const googleMapsClient = googleMaps.createClient({
    key: 'AIzaSyC0HC2Turfkrofrofkroes1sbMLG5k'
  });

答案 1 :(得分:1)

感谢@Romen我弄清楚了,下面是修复程序,现在它可以作为JS代码使用。.

import * as MapsClient from "@google/maps";

const googleMapsClient = MapsClient.createClient({ key: "AIzaSyC0HC2Tuekjrekfjkfj1sbMLG5k"});